简体   繁体   中英

Entity Framework Rest API Change entity

I have an entity stored in a database and am trying to expose it via api for select update and delete. The problem is that the final shape of the entity is not the same shape as it is stored. How to i incorporate the code to do this.

Entity is ScheduleTemplate

public int id { get; set; }
public int templateId { get; set; }
public int resourceId { get; set; }
public int titleId { get; set; }
public int dow { get; set; }
public int duration { get; set; }
public string startTimeStr { get; set; }

but what needs to be exposed is the above but instead of the dow,Duration and StartimeStr fields i want To use them to compute two fields StarDate And EndDate.

Where startdate = The date relative to the current Day of week (dow) with the starttimeStr as a datetime. Enddate = startdate + duration (mins)

I would like this to be Done noth ways .ie we need to derive startdate/enddate when sending to client and need to derive dow,startimestr and duration from when startdate/enddate receiving from client to save.

If anybody could help me with a way to solve this problem. thank you in advance.

All you need is some sort of converter pattern, which should work both ways:

public class EntityViewModel
{
    public int id { get; set; }
    public int templateId { get; set; }
    public int resourceId { get; set; }
    public int titleId { get; set; }
    public int dow { get; set; }
    public DateTime startDate { get; set; }
    public DateTime endDate { get; set; }
}

public interface IEntityConverter
{
    Entity Convert(ViewModel viewModel);
    ViewModel Convert(Entity entity);
}

public class EntityConverter
{
    public Entity Convert(EntityViewModel viewModel)
    {
        return new Entity
        {
            id = viewModel.id,
            templateId = viewModel.templateId,
            resourceId = viewModel.resourceId,
            titleId = viewModel.titleId,
            dow = viewModel.dow,
            startTimeStr = viewModel.startDate.ToString(),
            duration = (int)((viewModel.endDate - viewModel.startDate).Ticks)
        };
    }

    public EntityViewModel Convert(Entity entity)
    {
        var startDate = DateTime.Parse(entity.startTimeStr);
        return new EntityViewModel
        {
            id = entity.id,
            templateId = entity.templateId,
            resourceId = entity.resourceId,
            titleId = entity.titleId,
            dow = entity.dow,
            startDate = startDate,
            endDate = startDate.AddTicks(entity.duration)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM