派生类中的复合键

时间:2014-03-28 12:35:02

标签: c# entity-framework

使用继承时,我会更多地了解复合键。

看看我的问题:

    public class User
    {
        public User()
        {
            Contacts = new List<ContactUser>();
        }

        [Key]
        public int ID { get; set; }

        public virtual string Nom { get; set; }

        public virtual List<ContactUser> Contacts { get; set; }
    }

    public class Contact
    {
        [Key, Column(Order = 1)]
        public int ID { get; set; }

        public virtual string Nom { get; set; }
    }

    [Table("ContactUsers")]
    public class ContactUser : Contact
    {
        [Key, Column(Order = 2)]
        public int User_ID { get; set; }
        [ForeignKey("User_ID")]
        public virtual User User { get; set; }
    }

ContactUser具有以下复合键{ID,User_ID},User_ID是以用户为目标的不可为空的外键。当我删除ContactUser和他的用户之间的关系时,我期待EF将ContactUser声明为已删除。当我没有将联系人映射到模型时,哪个工作正常。

见:

    public class Context : DbContext
    {
        public Context(string connectionString)
            : base(connectionString)
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>();
            modelBuilder.Entity<ContactUser>();
            base.OnModelCreating(modelBuilder);
        }
    }

    static void Main(string[] args)
    {
        try
        {
            using (var context = new Context("TestAdhoc"))
            {
                User User = new User() { Nom = "Hello" };
                ContactUser contact = new ContactUser() { Nom = "World" };
                User.Contacts.Add(contact);
                context.Set<User>().Add(User);
                context.SaveChanges();
            }

            using (var context = new Context("TestAdhoc"))
            {
                User User = context.Set<User>().Single(c => c.Nom == "Hello");
                ContactUser Contact = User.Contacts.Single(c => c.Nom == "World");
                Console.WriteLine(string.Format("Contact Loaded : {0}", context.Entry<ContactUser>(Contact).State));
                User.Contacts.Remove(Contact);
                Console.WriteLine(string.Format("Relationship Removed : {0}", context.Entry<ContactUser>(Contact).State));
                context.SaveChanges();
            }
        }
        catch(Exception e)
        {

        }
    }

输出:

Contact Loaded : Unchanged
Relationship Removed : Deleted

但现在,我映射联系人:

    public class Context : DbContext
    {
        public Context(string connectionString)
            : base(connectionString)
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>();
            modelBuilder.Entity<Contact>();
            modelBuilder.Entity<ContactUser>();
            base.OnModelCreating(modelBuilder);
        }
    }

输出:

Loaded : Unchanged
Removed : Modified

如您所见,行为已不再相同。

有意吗? 我是否有办法让第一个行为发生并仍然映射联系人?

0 个答案:

没有答案