2011-09-22 60 views
0

因此,拼命試圖將EntityFramework變成可用的。我在這裏..C#Linq正在從我的實體中刪除一個值

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是庫這個方法是一個實例變量。

的問題是,當我打電話的SubmitChanges,放在methodID在新附加的副本中的值被送到該服務器爲0,如果在附件之後但在提交之前將其打印出來,實際上不是零。我幾乎可以肯定,這與該字段是一個外鍵相關,但我仍不明白爲什麼當Linq有一個符合外鍵約束條件的有效值時,它會將其任意設置爲零。

我在這裏錯過了什麼?

+0

ü使用的是什麼實體框架版本R? – Boomer

+1

'Attach'後直接調用'SaveChanges'什麼都不做。 'Attach'將一個實體置於'Unchanged'狀態。如果您在連接後不再更改實體,則EF不會向DB發送任何命令。這個'ent'的目的是什麼?你傳入'Attach'的'o'是什麼?你的'Attach'做什麼? EF的「Attach」沒有兩個參數。 'SubmitChanges'只是對'SaveChanges'的調用還是更多? – Slauma

+0

你可以顯示'_ctx.MyEntities.Attach(...,...)'裏面的代碼嗎? – Slauma

回答

1

您應該設置Method = orig.Method,但我無法看到您的dbml。

+0

如果我附加引用,它將嘗試在提交更改時插入該實體,顯然這會在Method表上引起pk問題 – user959620

0

我認爲你需要重視外鍵參考

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(); 
相關問題