实体框架、代码优先、更新"one to many"与独立关联的关系



我花了很长时间才找到下面描述的场景的解决方案。一件看似简单的事情竟然变得相当困难。问题是:

使用实体框架4.1(代码优先方法)和"独立关联",我如何在"分离"场景中为现有的"多对一"关系分配不同的端。

模型:

我意识到使用ForeignKey关系而不是独立关联是一种选择,但我更倾向于在Pocos中不使用ForeignKey实现。

客户有一个或多个目标:

    public class Customer:Person
{
    public string Number { get; set; }
    public string NameContactPerson { get; set; }
    private ICollection<Target> _targets;
    // Independent Association
    public virtual ICollection<Target> Targets
    {
        get { return _targets ?? (_targets = new Collection<Target>()); }
        set { _targets = value; }
    }
}

Target有一个Customer:

    public class Target:EntityBase
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Note { get; set; }
    public virtual Address Address { get; set; }
    public virtual Customer Customer { get; set; }
}

Customer派生自Person类:

    public class Person:EntityBase
{        
    public string Salutation { get; set; }
    public string Title { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set  ; }        
    public string Telephone1 { get; set; }
    public string Telephone2 { get; set; }
    public string Email { get; set; }        
    public virtual Address Address { get; set; }
}

EntityBase类提供了一些常用属性:

    public abstract class EntityBase : INotifyPropertyChanged
{
    public EntityBase()
    {
        CreateDate = DateTime.Now;
        ChangeDate = CreateDate;
        CreateUser = HttpContext.Current.User.Identity.Name;
        ChangeUser = CreateUser;
        PropertyChanged += EntityBase_PropertyChanged;
    }
    public void EntityBase_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (Id != new Guid())
        {
            ChangeDate = DateTime.Now;
            ChangeUser = HttpContext.Current.User.Identity.Name;
        }
    }
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public Guid Id { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime? ChangeDate { get; set; }
    public string CreateUser { get; set; }
    public string ChangeUser { get; set; }
}

的背景:

    public class TgrDbContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Target> Targets { get; set; }
    public DbSet<ReportRequest> ReportRequests { get; set; }
    // If OnModelCreating becomes to big, use "Model Configuration Classes"
    //(derived from EntityTypeConfiguration) instead
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().HasOptional(e => e.Address);            
        modelBuilder.Entity<Customer>().HasMany(c => c.Targets).WithRequired(t => t.Customer);            
    }
    public static ObjectContext TgrObjectContext(TgrDbContext tgrDbContext)
    {           
        return ((IObjectContextAdapter)tgrDbContext).ObjectContext;
    }
}

我等待@Martin的回答,因为这个问题还有更多的解决方案。这里是另一个(至少它与ObjectContext API一起工作,所以它也应该与DbContext API一起工作):

// Existing customer
var customer = new Customer() { Id = customerId };
// Another existing customer
var customer2 = new Customer() { Id = customerId2 };
var target = new Target { ID = oldTargetId };
// Make connection between target and old customer
target.Customer = customer;
// Attach target with old customer
context.Targets.Attach(target);
// Attach second customer
context.Customers.Attach(customer2);
// Set customer to a new value on attached object (it will delete old relation and add new one)
target.Customer = customer2;
// Change target's state to Modified
context.Entry(target).State = EntityState.Modified;
context.SaveChanges();

这里的问题是EF内部的状态模型和状态验证。具有强制关系(多侧)的未更改或修改状态的实体,在删除状态没有关联的情况下,不能在添加状态独立关联。不允许修改关联状态

关于这个话题有很多信息可以找到;在stackoverflow上,我发现Ladislav Mrnka的见解特别有用。更多的主题也可以在这里找到:实体框架的NTier改进和实体框架4的新功能?

在我的项目(Asp。Net Webforms),用户可以选择将分配给Target对象的Customer替换为不同的(现有的)Customer对象。此事务由绑定到ObjectDataSource的FormView控件执行。ObjectDataSource与项目的BusinessLogic层通信,后者依次将事务传递给DataAccess层中Target对象的存储库类。存储库类中目标对象的Update方法如下所示:

    public void UpdateTarget(Target target, Target origTarget)
    {
        try
        {
            // It is not possible to handle updating one to many relationships (i.e. assign a 
            // different Customer to a Target) with "Independent Associations" in Code First.
            // (It is possible when using "ForeignKey Associations" instead of "Independent 
            // Associations" but this brings about a different set of problems.)
            // In order to update one to many relationships formed by "Independent Associations"
            // it is necessary to resort to using the ObjectContext class (derived from an 
            // instance of DbContext) and 'manually' update the relationship between Target and Customer. 
            // Get ObjectContext from DbContext - ((IObjectContextAdapter)tgrDbContext).ObjectContext;
            ObjectContext tgrObjectContext = TgrDbContext.TgrObjectContext(_tgrDbContext);
            // Attach the original origTarget and update it with the current values contained in target
            // This does NOT update changes that occurred in an "Independent Association"; if target
            // has a different Customer assigned than origTarget this will go unrecognized
            tgrObjectContext.AttachTo("Targets", origTarget);
            tgrObjectContext.ApplyCurrentValues("Targets", target);
            // This will take care of changes in an "Independent Association". A Customer has many
            // Targets but any Target has exactly one Customer. Therefore the order of the two
            // ChangeRelationshipState statements is important: Delete has to occur first, otherwise
            // Target would have temporarily two Customers assigned.
            tgrObjectContext.ObjectStateManager.ChangeRelationshipState(
                origTarget,
                origTarget.Customer,
                o => o.Customer,
                EntityState.Deleted);
            tgrObjectContext.ObjectStateManager.ChangeRelationshipState(
                origTarget,
                target.Customer,
                o => o.Customer,
                EntityState.Added);
            // Commit
            tgrObjectContext.Refresh(RefreshMode.ClientWins, origTarget);
            tgrObjectContext.SaveChanges();
        }
        catch (Exception)
        {
            throw;
        }
    }            

这适用于Target对象的Update方法。值得注意的是,插入新Target对象的过程要简单得多。DbContext正确地识别独立关联的Customer端,并将更改提交到数据库,无需进一步操作。存储库类中的Insert方法如下所示:

        public void InsertTarget(Target target)
    {
        try
        {
            _tgrDbContext.Targets.Add(target);
            _tgrDbContext.SaveChanges();
        }
        catch (Exception)
        {
            throw;
        }
    }

希望这对处理类似任务的人有用。如果您注意到上述方法的问题,请在您的评论中告诉我。谢谢!

最新更新