开发者

C# Linq is removing a value from my entity

开发者 https://www.devze.com 2023-04-06 14:36 出处:网络
So, in a desperate attempt to wrangle EntityFramework into being usable. I am here.. private MyEntity Update(MyEntity orig)

So, in a desperate attempt to wrangle EntityFramework into being usable. I am here..

private MyEntity Update(MyEntity orig) 
{
    //need a fresh copy so we can attach without adding timestamps
    //to every table....
    MyEntity ent;
    using (var db = new DataContext()) 
    {
        ent = db.MyEntities.Single(x => x.Id == orig.Id);
    }

    //fill a new one with the values of the one we want to save
    var cpy = new Payment()
    {
        //pk
        ID = orig.ID,
        //foerign key
        MethodId = orig.MethodId,
        //other fields
        Information = orig.Information,
        Amount = orig.Amount,
        Approved = orig.Approved,
        AwardedPoints = orig.AwardedPoints,
        DateReceived = orig.DateReceived
    };
    //attach it
    _ctx.MyEntities.Attach(cpy, ent);

    //submit the changes
    _ctx.SubmitChanges();
}

_ctx is an instance variable for the repository this method is in.

The problem is that when I call SubmitChanges, the value of MethodId in the newly attached copy is sent to the server as 0, when it is in fact not zero if I pr开发者_开发百科int it out after the attach but before the submit. I am almost certain that is related to the fact that the field is a foreign key, but I still do not see why Linq would arbitrarily set it to zero when it has a valid value that meets the requirements of the constraint on the foreign key.

What am I missing here?


You should probably set Method = orig.Method, but I can't see your dbml, of course.


I think you need to attach the foreign key reference

var cpy = new Payment()
{
    //pk
    ID = orig.ID,
    //other fields
    Information = orig.Information,
    Amount = orig.Amount,
    Approved = orig.Approved,
    AwardedPoints = orig.AwardedPoints,
    DateReceived = orig.DateReceived
};

//create stub entity for the Method and Add it.
var method = new Method{MethodId=orig.MethodId)
_ctx.AttachTo("Methods", method);
cpy.Methods.Add(method);

//attach it
_ctx.MyEntities.Attach(cpy, o);

//submit the changes
_ctx.SubmitChanges();
0

精彩评论

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

关注公众号