自追踪 poco
我有一个像这样的 poco 类
public Profile
{
public virtual int ID
{
get;
set;
}
public virtual string Description
{
get;
set;
}
public virtual bool Enabled
{
get;
set;
}
}
当我尝试像这样更新时
var prof = new Profile(){ ID = 1, Enabled = false };
context.Profiles.Single (s => s.ID == 1);
context.Profiles.ApplyCurrentValues(prof);
context.SaveChanges();
Sql 对我说 Description 不允许 NULL,但我没有更新“Description”列,我只想更新“Enabled”字段。
怎么了?
塔克斯
I have a poco class like this
public Profile
{
public virtual int ID
{
get;
set;
}
public virtual string Description
{
get;
set;
}
public virtual bool Enabled
{
get;
set;
}
}
When i try to update like this
var prof = new Profile(){ ID = 1, Enabled = false };
context.Profiles.Single (s => s.ID == 1);
context.Profiles.ApplyCurrentValues(prof);
context.SaveChanges();
Sql says to me that Description does not allow NULL, but i'm not updating the "Description" column, I want to update just the "Enabled" field.
What's wrong?
Tks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请尝试以下操作:
如您所见,我不需要先从数据库加载实体。我能够设置在分离实体上修改哪个属性。
Try this instead:
As you can see I didn't need to load the entity first from database. I was able to set which property was modified on detached entity.
根据我的评论:在不了解 EF4 的情况下,我希望它的工作方式如下:
假设
Single
是 Linq Single,那么它将返回一个您应该修改的值。Based on my comment: Without knowing EF4, this is how I'd expect it to work:
Assuming
Single
is the Linq Single, then it will return a value that you should modify.这不行吗?
我认为问题在于您从未跟踪的对象调用ApplyCurrentValues - 这意味着它不知道哪些属性已更改和未更改,因此它只是复制所有属性,包括那些为空的 - 在你的情况描述中。
如果要修改从数据上下文加载的实体的值,则无需调用ApplyCurrentValues。
Does this not work?
I think the problem is that you're calling ApplyCurrentValues from an untracked object - this means that it has no idea which properties have and haven't been changed, so it just copies across all the properties, including the ones that are null - in your case Description.
You don't need to call ApplyCurrentValues if you are modifying the values of an entity that is loaded from the data context.