2016-01-20 68 views
0

假定下列:保持實體引用乾淨而不保存到數據庫

2的entites(Address < - (m爲1) - >City),一個Address(由它們的ID FK)具有一個City

class Address 
{ 
    public Guid AddressId {get;set;} 
    public Guid AddressCityId {get;set;} 

    public City CityEntity {get;set;} 

    public string CityName { get { return CityEntity.Name; } 

    public void SetCity(DbContext ctx, City c) 
    { 
     AddressCityId = c.CityId; 

     // here I need some kind of refresh 
     this.CityEntity == null; // true    

     ctx.ObjectContext.Refresh(RefreshMode.ClientWins, this); // fails 
     ctx.ObjectContext.Refresh(RefreshMode.StoreWins, this); // fails    
    } 
} 

class City 
{ 
    public Guid CityId {get;set;} 
    public string Name {get;set;} 
} 

我想逐步創建值並將其保存在數據庫中。根據我的理解,兩個實體都存在於ObjectStateManager上下文中,但彼此不知道(也不參考)。 如何在不調用SaveChanges()的情況下實現此目的?

也嘗試附加實體。但是這會導致SaveChanges失敗,因爲所有實體都有狀態Unmodified

編輯#1

目前我正在運行此(簡化)代碼(這仍然是不工作):

using(var context = new DbContext()) 
{ 
    var city = new City(){Name = "New York"}; 
    context.Set<City>.Add(city); 
    context.ChangeTracker.DetectChanges(); 

    var address = new Address(); 
    context.Set<Address>.Add(address); 
    context.ChangeTracker.DetectChanges(); 

    // at this point, both entities have the state `Added` 

    // set FK manually and call update 
    address.AddressCityId = city.CityId; 
    context.ChangeTracker.DetectChanges(); 

    address.CityName == null; // reference is still null 
} 

編輯#2

致電時context.SaveChanges()Add之後它起作用,截至目前,已添加的實體已設置爲EntityKey。 有沒有什麼方法可以手動設置EntityKey(EF6),因爲Guid總是由客戶端而不是數據庫生成的?

+0

我認爲您使用代碼優先來設計模型。 EF具有用於生成表/實體之間關係的標準命名方案。如果你不遵循它,你需要使用流利的語法來在OnModelCreated()事件中聲明它們。 –

+0

@MattiasÅslund不,它是數據庫優先(真實的)。這只是示例代碼來展示我想要做的事情。所以,命名是(不是顯示)生成和正確。 – KingKerosin

回答

0

在SaveChanges方法(和其他一些方法)期間,調用了修復關係的DetectChanges方法。只需撥打電話:

context.ChangeTracker.DetectChanges() 
+0

不幸的是,這是行不通的。看看我的'編輯#1'看看我到目前爲止。 – KingKerosin