实体框架4.1插入错误
我已经为我的有问题的基本窗口编写了一个通用存储库。 更具体地说,有一个名为 Unit 的小 poco 类,如下所示:
public class Unit : BaseEntity
{
public string Name { get; set; }
private ICollection<Good> _goods;
public virtual ICollection<Good> Goods
{
get
{
if(_goods==null)
{
return new List<Good>();
}
return _goods;
}
set { _goods = value; }
}
}
它是从基实体类继承的:
public class BaseEntity
{
public int Id { get; set; }
public override string ToString()
{
return Id.ToString();
}
}
这是我的通用存储库类的添加部分:
public void Add(TEntity entity)
{
if (entity == null) return;
if (Context.Entry(entity).State == EntityState.Detached)
{
Context.Set<TEntity>().Attach(entity);
}
Context.Set<TEntity>().Add(entity);
Context.SaveChanges();
}
在添加新记录之前,从数据库获取最大 id 并放置在 IdTextBox 中,并调用基本表单的 add 方法,该方法调用前面提到的基本存储库的 Add 方法。问题是,我收到此错误,“属性‘Id’是对象关键信息的一部分,无法修改。” 还有一个映射器类,它将每个属性映射到其相应的控件,该控件可以很好地完成其工作。 我的问题是什么?
提前致谢。
i have written a generic repository for my base windows which have a problem with.
lets be more specific, there is a little poco class called Unit as following:
public class Unit : BaseEntity
{
public string Name { get; set; }
private ICollection<Good> _goods;
public virtual ICollection<Good> Goods
{
get
{
if(_goods==null)
{
return new List<Good>();
}
return _goods;
}
set { _goods = value; }
}
}
which is inherited from a base entity class as :
public class BaseEntity
{
public int Id { get; set; }
public override string ToString()
{
return Id.ToString();
}
}
and this is my Add section of generic repository class:
public void Add(TEntity entity)
{
if (entity == null) return;
if (Context.Entry(entity).State == EntityState.Detached)
{
Context.Set<TEntity>().Attach(entity);
}
Context.Set<TEntity>().Add(entity);
Context.SaveChanges();
}
before add a new record, max id is fetched from db and placed in IdTextBox and them add method of base form is called which calls aforementioned Add method of base repository. here is the problem, i get this error, "The property 'Id' is part of the object's key information and cannot be modified."
there is also a mapper class that maps every property to its corresponding control which does its job fine.
What is my problem?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现这个问题是由于自动检测更改启用而发生的,这是事实。
i figured out that this problem is occured because of auto detect changes enability which was true.