【发布时间】:2018-04-11 13:33:58
【问题描述】:
情况:我的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);
我对@987654331@ 和EMail 课程重复了这一点。
之后我映射这两个类;
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
有人可以帮我解决这个问题吗?非常感谢
【问题讨论】:
标签: c# entity-framework