保持实体引用清洁而不保存到数据库

时间:2016-01-20 14:57:15

标签: c# entity-framework entity-framework-6

鉴于以下内容:

2个Entites(Address&lt ;-(m:1) - > City),Address有一个City(其ID为FK)

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;}
}

我想逐步创建值,最后将它们保存在数据库中。

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

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

    address.SetCity(context, city);

    address.CityName == null; // true -> I want it to be "New York"

    // save all at the end
    context.SaveChanges();
}

根据我的理解,两个实体都存在于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总是由客户端而不是数据库生成?

1 个答案:

答案 0 :(得分:0)

在SaveChanges方法(以及其他一些方法)中,调用了FixctChanges方法来修复关系。请致电:

context.ChangeTracker.DetectChanges()