保存一个具有m-t-m关系的实体与DB中的另一个实体重复?

时间:2017-01-25 12:58:26

标签: entity-framework

我有两个有多对多关系的实体,我保存了一个有实体列表的实体,但它们是重复的 例如:

class GENEntity
{
    int Id { get; set; }
    string Name { get; set; }
    List<GENEntityTab> tabs { get; set; }
}
class GENEntityTab
{
    int Id { get; set; }
    string Name { get; set; }
    List<GENEntity> entities { get; set; }
}

当我保存GENEntity的对象但作为视图模型时,您将看到下一个,并列出两个GENEntityTab,这两个标签会在数据库中插入(重复)。我正在使用Web API和angular

在Repository中,只有在我点击提交时才会调用它(还有一些额外的属性):

  public static JsonViewData AddOrUpdate(ModelDBContext context, GENEntityViewModel entityVM, string name, string id)
    {
        try
        {
            var entity = context.Entities.SingleOrDefault(x => x.Id == entityVM.Id);

            if (entity == null)
            {
                entity = new GENEntity();
                entity.InjectFrom(entityVM);
                context.Entities.Add(entity);
            }
            else
            {
                entity.DateUpdated = DateTime.Now;
                entity.InjectFrom(entityVM);
            }
            entity.CreatedById = new Guid(id);
            entity.LastUpdatedById = new Guid(id);
            context.SaveChanges();
            return new JsonViewData { IsSuccess = true, Message = "Created Successfully" };
        }
        catch (Exception ex)
        {
            return new JsonViewData { IsSuccess = false, Message = ex.Message };
        }
    }

视图模型:

public class GENEntityTabViewModel
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<GENEntity> Entities { get; set; } = new List<GENEntity>();

        public GENEntityTabViewModel()
        {

        }

        public GENEntityTabViewModel(GENEntityTab entityTab)
        {
            Id = entityTab.Id;
            Name = entityTab.Name;
            Description = entityTab.Description;
            Entities = entityTab.Entities;
        }
    }

0 个答案:

没有答案