具有Id和对象的实体框架导航属性失败

时间:2014-07-02 18:29:08

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

保存动态定义导航属性的实体时会导致问题。

这是一个更复杂的代码的复制品。

namespace ConsoleAppEFAttaching
{
    public class MyContext : DbContext
    {
        public MyContext()
            : base("MyContextConnectionString")
        {
            base.Configuration.LazyLoadingEnabled = false;
            base.Configuration.AutoDetectChangesEnabled = false;
            base.Configuration.ProxyCreationEnabled = false;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Parent>();
            modelBuilder.Entity<Child>();
        }
    }
    public class Parent
    {
        public int Id { get; set; }
        public string NameParent { get; set; }

        public static Parent Create(int id)
        {
            return new Parent { Id = id };
        }
    }

    public class Child
    {
        private Parent theOnlyParent;
        public int Id { get; set; }
        public string NameChild { get; set; }

        public Parent TheOnlyParent {
            get { return Parent.Create(TheOnlyParentId); }
            set { TheOnlyParentId = value.Id; }
        }

        public int TheOnlyParentId { get; set; }
    }


    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Start create database");
            Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
            Console.WriteLine("Start adding Parent");
            var p1 = new Parent {NameParent = "Test Parent Name#1"};
            int parentCreatedId;
            Console.WriteLine("Context");
            using (var context = new MyContext())
            {
                context.Set<Parent>().Add(p1);
                context.SaveChanges();
                parentCreatedId = p1.Id;
            }
            Console.WriteLine("Start adding a child from a different context");
            var c1 = new Child { NameChild= "Child #1" };
            c1.TheOnlyParentId = parentCreatedId;
            c1.TheOnlyParent = new Parent {Id = parentCreatedId};
            Console.WriteLine("Context");
            using (var context = new MyContext())
            {
                Console.WriteLine("*Change State Child");
                context.Entry(c1).State = EntityState.Added; // !!! Error : Conflicting changes to the role 'Child_TheOnlyParent_Target' of the relationship 'Child_TheOnlyParent' have been detected.
                Console.WriteLine("*Change State Child->Parent Navigability Property");
                context.Entry(c1.TheOnlyParent).State = EntityState.Detached;
                Console.WriteLine("*Save Changes");
                context.SaveChanges();
            }
            Console.WriteLine("End");
            Console.ReadLine();
        }
    }
}

问题在于将Entry State更改为Added。错误Conflicting changes to the role 'Child_TheOnlyParent_Target' of the relationship 'ConsoleAppEFAttaching.Child_TheOnlyParent' have been detected.会引发。

如果我将一个Console.WriteLine放在Child.TheOnParent属性中,我看到该方法已设置并在状态更改期间多次获取。我虽然问题可能是由于返回的对象不一致引起的,但即使我创建了一次(仅实例化第一次然后返回相同的实例)它也有同样的问题。

如果我不在Child.OnlyParent中使用Parent.Create,它可以工作。但是,我想使用我们的逻辑(使用Create方法)仅在我们要为性能原因限制Include的情况下通过id定义类。

所以我的问题分为两部分:为什么在更改状态期间它会多次调用Getter和Setter?为什么我对角色进行了相互冲突的更改?

2 个答案:

答案 0 :(得分:1)

由于context.Entry(c1)方法调用而调用getter和setter。 这里发生的是,当你为一个分离的对象调用这个方法时,ChangeTracker将整个对象图(该对象及其所有的navigationproperties递归地)附加到Context。这就是吸气者被召唤的原因。

如果匹配,ChangeTracker还会尝试修复已附加对象的导航属性。因此,如果您的DbContext已将Parent.Id = 1附加到您的上下文,并且在context.Entry(c1)调用Child.Parent之后附加Child with Child.ParentId = 1且Child.Parent navigation property = null财产自动填写。这就是调用setter的原因。

正如您所假设的,您的问题是每次访问getter时都会创建一个新的Parent对象实例。对于EF来说,基本上就像具有相同主键的对象的多个实例一样,ChangeTracker无法处理。 更改这样的导航和外键属性应该有效。

public Parent TheOnlyParent
{
    get
    {
        if (theOnlyParent == null) {
            theOnlyParent = Parent.Create(TheOnlyParentId);
        }
        return theOnlyParent;
    }
    set
    {
     If(theOnlyParent != value){
            theOnlyParent = value;
            if (value != null) {
                TheOnlyParentId = value.Id;
            }
        }
    }
}

private int theOnlyParentId;

public int TheOnlyParentId
{
    get
    {
        return theOnlyParentId;
    }
    set
    {
        if (theOnlyParentId != value) {
            theOnlyParentId = value;
            theOnlyParent = null;
        }
    }
}

答案 1 :(得分:0)

我需要改变一些东西以使其有效。

首先,我们需要让Child返回对象。原因是,如果有人将导航设置为Null,我们可以将属性设置为Null并同时保留ID。

public class Child
{
    private Parent theOnlyParent;
    private int theOnlyParentId;
    public int Id { get; set; }
    public string NameChild { get; set; }
    [Required]
    public Parent TheOnlyParent
    {
        get
        {
            return theOnlyParent;
        }
        set
        {
            theOnlyParent = value;
            if (value != null)
                TheOnlyParentId = value.Id;
        }
    }

    public int TheOnlyParentId  
    {
        get { return theOnlyParentId; }
        set { 

            theOnlyParentId = value;
            theOnlyParent = Parent.Create(value);
        }
    }

}

第二件事是与实体合作。我可以将TheOnlyParent设置为null并保持Id或我可以使用上下文的Entry并设置为Unchanged。两者现在都有效。

using (var context = new MyContext())
        {
            Console.WriteLine("*Change State Child");
            context.Entry(c1).State = EntityState.Added; // Conflicting changes to the role 'Child_TheOnlyParent_Target' of the relationship 'Child_TheOnlyParent' have been detected.
            Console.WriteLine("*Change State Child->Parent Navigability Property");
            context.Entry(c1.TheOnlyParent).State = EntityState.Unchanged; // We do not want to create but reuse
            Console.WriteLine("*Save Changes");
            context.SaveChanges();
        }

如果有人想尝试整个解决方案,请输入以下完整代码:

public class MyContext : DbContext
{
    public MyContext()
        : base("MyContextConnectionString")
    {
        base.Configuration.LazyLoadingEnabled = false;
        base.Configuration.AutoDetectChangesEnabled = false;
        base.Configuration.ProxyCreationEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Parent>();
        modelBuilder.Entity<Child>();
    }
}
public class Parent
{
    public int Id { get; set; }
    public string NameParent { get; set; }

    public static Parent Create(int id)
    {
        return new Parent { Id = id };
    }
}

public class Child
{
    private Parent theOnlyParent;
    private int theOnlyParentId;
    public int Id { get; set; }
    public string NameChild { get; set; }
    [Required]
    public Parent TheOnlyParent
    {
        get
        {
            return theOnlyParent;
        }
        set
        {
            theOnlyParent = value;
            if (value != null)
                TheOnlyParentId = value.Id;
        }
    }

    public int TheOnlyParentId  
    {
        get { return theOnlyParentId; }
        set { 

            theOnlyParentId = value;
            theOnlyParent = Parent.Create(value);
        }
    }

}


class Program
{

    static void Main(string[] args)
    {
        Console.WriteLine("Start create database");
        Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
        Console.WriteLine("Start adding Parent");
        var p1 = new Parent {NameParent = "Test Parent Name#1"};
        int parentCreatedId;
        Console.WriteLine("Context");
        using (var context = new MyContext())
        {
            context.Set<Parent>().Add(p1);
            context.SaveChanges();
            parentCreatedId = p1.Id;
        }
        Console.WriteLine("Start adding a child from a different context");
        var c1 = new Child { NameChild= "Child #1" };
        c1.TheOnlyParentId = parentCreatedId;
        c1.TheOnlyParent = new Parent {Id = parentCreatedId};

        Console.WriteLine("Context");
        using (var context = new MyContext())
        {
            Console.WriteLine("*Change State Child");
            context.Entry(c1).State = EntityState.Added; // Conflicting changes to the role 'Child_TheOnlyParent_Target' of the relationship 'Child_TheOnlyParent' have been detected.
            Console.WriteLine("*Change State Child->Parent Navigability Property");
            context.Entry(c1.TheOnlyParent).State = EntityState.Unchanged; // We do not want to create but reuse
            Console.WriteLine("*Save Changes");
            context.SaveChanges();
        }
        Console.WriteLine("End");
        Console.ReadLine();
    }
}