开发者

EF4.1 How to I implement a CascadeDelete where two tables share records in one table?

开发者 https://www.devze.com 2023-04-03 11:41 出处:网络
I\'m using EF4.1 Code First.I have two classes which both have a one-to-one relationship witha contact class.When I remove a rec开发者_开发知识库ord in either of the two classes I want the associated

I'm using EF4.1 Code First. I have two classes which both have a one-to-one relationship with a contact class. When I remove a rec开发者_开发知识库ord in either of the two classes I want the associated entry in the contact class removed also.

ex:

public class User
{
   public virtual int ID { get; set; }
   ...
   public virtual Contact Contact { get; set; }
}

public class Admin
{
   public virtual int ID { get; set; }
   ...
   public virtual Contact Contact { get; set; }
}

public class Contact
{
   public virtual int ID { get; set; }
   ...
}

I tried various things with annotations and fluent API but could not yet manage to get a cascade delete working. What is the correct way to implement this in EF 4.1 Code First?


I'm not sure but I think your contact entity needs User and Admin entities also..

Then the fluent api should work:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
                .HasRequired(u => u.Contact)
                .WithRequiredPrincipal(c => c.User)
                .WillCascadeOnDelete();

    modelBuilder.Entity<Admin>()
                .HasRequired(a => a.Contact)
                .WithRequiredPrincipal(c => c.Admin)
                .WillCascadeOnDelete();
}


I think this should work if you want to delete Users and Admins if a Contact is deleted:

public class User
{ 
   public int ID { get; set; }


   public int ContactId { get; set; }
   public virtual Contact Contact { get; set; }
}

public class Contact 
{
   public int ID { get; set; }
   public virtual List<User> Users {get; set;}

   public Contact()
   {
        Users = new List<User>();
   }
}

While I believe you want to do the opposite, which means you need to make the Contact is the dependent entity

public class User
{ 
   public int ID { get; set; }
   public bool IsAdmin {get; set;}
   public virtual List<Contact> {get; set;}

   public Contact()
   {
        Users = new List<User>();
   }
}

public class Contact 
{
   public int ID { get; set; }

   [ForiegnKey("Owner")]
   public int UserId {get; set;}
   public virtual User Owner {get; set;}
}

you can use other types of Inheritance other than TPC I'm using here, because DBMS doesn't support two mutually exclusive Foreign Keys

0

精彩评论

暂无评论...
验证码 换一张
取 消