具有相关条目的实体框架更新条目仅更新主条目

时间:2018-04-11 13:33:58

标签: c# entity-framework

情况:我的Main课程如下:

class Main 
{
    public int Id { get; set; }
    public Customer Customer { get; set; }
}

我的Customer课程如下:

class Customer 
{
    public int Id { get; set; }
    public Address Address { get; set; }
    public EMail Email { get; set; }
    public Language Language { get; set; }
}

问题:我在阅读使用语法时尽量使用上下文更好。所以我从数据库中取出主类,让它更改道具,然后更新主类。

问题是我的相关条目都是重复的。我尝试了几个建议:

第一种方法:

private object InsertOrUpdate<T, TKey>(T entity, Func<T, TKey>  idExpression) where T : class
{       
  var existingEntity = LokaleContext.Set<T>().Find(idExpression(entity));
  if (existingEntity != null)
  {
    if (LokaleContext.Entry(existingEntity).State == EntityState.Detached)
    {
      LokaleContext.Set<T>().Attach(existingEntity);
    }
    else
    {
      LokaleContext.Entry(existingEntity).CurrentValues.SetValues(entity);
    }

    return existingEntity;
  }
  else
  {
    LokaleContext.Set<T>().Add(entity);
    return entity;
  }
}

我使用此代码返回相关条目并将它们耦合回主类。

例如:

var customerFromDb = db.Set<Costumer>()
                       .Include(c => c.Address)
                       .Include(c => c.EMail)
                       .Include(c => c.Language)
                       .FirstOrDefault(c => c.Id == customerUsedLocal.Id);
customerUsedLocal.Customer.Address = InsertOrUpdate(customerFromDb.Customer.Address, a => a.Id);

我为LanguageEMail类重复此操作。

之后我映射了两个类;

MapObject(CustomerLoca, CustomerFromDb);
public object MapObject<T>(T entitySource, T entityDestination) where T : class
{
  var config = new MapperConfiguration(cfg => { cfg.CreateMap<T, T>(); });
  IMapper mapper = config.CreateMapper();
  return mapper.Map(entitySource, entityDestination);
}

最后我将CustomerFromDb的状态设置为已修改。

但无论我尝试做什么都没有,我尝试了所有这些链接而没有任何结果: - (

OptimisticConcurrencyException when persisting related entry

Entity Framework not updating existing related entity

Finding updated entry with Entity Framework Timestamp using code first

Entity Framework Updating with Related Entity

有人可以帮我解决这个问题。非常感谢

1 个答案:

答案 0 :(得分:0)

我终于做到了,我对给出的例子感到困惑并且混淆了事情。 所以这是我的解决方案 首先,我创建一个映射器配置文件

public class AutoMapperConfigurator:Profile
{

    public AutoMapperConfigurator()
    {
        CreateMap<Customer, Customer>()
            .ForMember(v=>v.Id, opt=>opt.Ignore())
            .ForMember(v=>v.Address,opt=>opt.Ignore())
            ;
    }
}

之后我转到存储库并执行以下代码:

//Get customer from db
var CustomerFromDb= LokaleContext.Set<Customer>().Include(c=>c.Address).FirstOrDefault(k => k.Id == Customer.Id);
//Couple the configfile to automapper
 var config = new MapperConfiguration(cfg => {cfg.AddProfile<AutoMapperConfigurator>();});
        IMapper mapper = config.CreateMapper();
//Map the two objects
        var CustomerforDb= mapper.Map(Customer, CustomerFromDb);
        //Get the address from the Db and couple it to the newly coupled      //entrie
        CustomerforDb.Address= LokaleContext.Set<Address>().SingleOrDefault(k=>k.Id==LichaamsBouw.Klant.Id);

        //save in db.
        LokaleContext.SaveChanges();