假定下列:保持实体引用干净而不保存到数据库
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
总是由客户端而不是数据库生成的?
我认为您使用代码优先来设计模型。 EF具有用于生成表/实体之间关系的标准命名方案。如果你不遵循它,你需要使用流利的语法来在OnModelCreated()事件中声明它们。 –
@MattiasÅslund不,它是数据库优先(真实的)。这只是示例代码来展示我想要做的事情。所以,命名是(不是显示)生成和正确。 – KingKerosin