2012-06-03 18 views
0

我一直在ASP.NET MVC3應用程序中使用代碼優先技術。這是非常基本的問題,即如何更新導航屬性。以下是詳細的代碼。如何在ASP.NET MVC3中使用代碼優先保存導航屬性

public class Destination 
    { 
     public int ID {get;set;} 
     // some other properties 
     public Country {get;set;} 
    } 

    public class Country 
    { 
    int ID {get;set;} 
    string Name {get;set;} 
    } 

    //i have simple structure as above. when i go to update destination entity. Country is not getting updated.even i tried following: 

    _db.Entry(Destination.Country).State = System.Data.EntityState.Modified; 
    _db.Entry(Destination).State = System.Data.EntityState.Modified; 
    //_db.ChangeTracker.DetectChanges(); 
    _db.SaveChanges(); 

其次,當我去添加它工作正常。是否需要明確規定foriegnKey關係?

回答

0

您可以通過三種方式添加實體:

調用上DbSet的Add()方法。這會使實體進入添加狀態,這意味着它將在下次調用SaveChanges()時插入到數據庫中。

context.Destination.Add(yourDestination); 

將其狀態更改爲已添加。

context.Entry(yourDestination).State = EntityState.Added; 

掛鉤它到已被跟蹤

context.Destination.Country.Add(yourCountry); 

方面的另一實體添加一個新的實體範圍內。

相關問題