C# 如何使用EF6中的现有行数据向表中添加新行?
使用EF6。 我正在对我的上下文实例调用一个方法:C# 如何使用EF6中的现有行数据向表中添加新行?,c#,.net,entity-framework,crud,C#,.net,Entity Framework,Crud,使用EF6。 我正在对我的上下文实例调用一个方法: var usr = context.Get<User>("Doe"); 然后,我尝试调用以下方法,该方法在我的上下文类中声明: public TEntity InsertOrUpdate<TEntity>(TEntity entityInstance) where TEntity : BaseEntity { if (entityInstance is IChangable)
var usr = context.Get<User>("Doe");
然后,我尝试调用以下方法,该方法在我的上下文类中声明:
public TEntity InsertOrUpdate<TEntity>(TEntity entityInstance) where TEntity : BaseEntity
{
if (entityInstance is IChangable)
{
this.Entry<TEntity>((TEntity)entityInstance).State = EntityState.Added;
this.SaveChanges();
return (TEntity)newInstance;
}
else
{
if (entityInstance.ID == default(int))
{
this.Set<TEntity>().Add(entityInstance);
}
else
{
this.Entry<TEntity>(entityInstance).State = EntityState.Modified;
}
this.SaveChanges();
return entityInstance;
}
}
public tenty InsertOrUpdate(tenty-entityInstance),其中tenty:BaseEntity
{
if(entityInstance可更改)
{
this.Entry((tenty)entityInstance.State=EntityState.Added;
这是SaveChanges();
返回(tenty)newInstance;
}
其他的
{
if(entityInstance.ID==默认值(int))
{
this.Set().Add(entityInstance);
}
其他的
{
this.Entry(entityInstance).State=EntityState.Modified;
}
这是SaveChanges();
返回entityInstance;
}
}
因此,据你所知,我期待以下行为:
如果我的用户类实现了IChangable接口(当然实现了),我希望表中的现有用户行不做任何更改,但顺便说一下,我希望我的上下文使用新ID和新LastName向表中添加一行。但它不起作用。现有行还具有LastName的新值。
有什么建议吗?您需要创建用户的副本,然后将其保存到数据库中。问题是EF不使用ID引用记录,而是使用实例化的对象在数据库中呈现记录。你可以阅读更多关于ORM的内容,这肯定比我解释得更好。是
entityInstance
在进入InsertOrUpdate
时附加到上下文中的吗?@GertArnold,是的。
public TEntity InsertOrUpdate<TEntity>(TEntity entityInstance) where TEntity : BaseEntity
{
if (entityInstance is IChangable)
{
this.Entry<TEntity>((TEntity)entityInstance).State = EntityState.Added;
this.SaveChanges();
return (TEntity)newInstance;
}
else
{
if (entityInstance.ID == default(int))
{
this.Set<TEntity>().Add(entityInstance);
}
else
{
this.Entry<TEntity>(entityInstance).State = EntityState.Modified;
}
this.SaveChanges();
return entityInstance;
}
}