开发者

Self tracking poco

开发者 https://www.devze.com 2023-02-27 05:14 出处:网络
I have a poco class like this public Profile { public virtual int ID { get; set; } public virtual string Description

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 Descript开发者_JS百科ion does not allow NULL, but i'm not updating the "Description" column, I want to update just the "Enabled" field.

What's wrong?

Tks


Try this instead:

var prof = new Profile { ID = 1, Enabled = false };
// Attach prof as unchanged entity
context.Profiles.Attach(prof);
// Get state entry for prof
ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(prof);
// Set only Enabled property to changed
entry.SetModifiedProperty("Enabled");
context.SaveChanges();

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.


Based on my comment: Without knowing EF4, this is how I'd expect it to work:

var prof = context.Profiles.Single (s => s.ID == 1);
prof.Enabled = false;
context.Profiles.ApplyCurrentValues(prof);
context.SaveChanges();

Assuming Single is the Linq Single, then it will return a value that you should modify.


Does this not work?

var prof = context.Profiles.Single(s => s.ID == 1);
prof.Enabled = false;
context.SaveChanges(); 

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号