Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

sql server ce - Cascade Delete Rule in EF 4.1 Code First when using Shared Primary Key Association

I implemented a bidirectional 1:1 relationship based on this answer:

Primary /Foreign Key in Entity Framework

I define the bidirectional relation this way:

public class Student
{   
    public virtual int StudentId { get; set; }
    public virtual Anamnesis Anamnesis { get; set; }

    . . .
}

public class Anamnesis
{
    [Key, ForeignKey("Student")]
    public int AnamnesisId { get; set; }

    public virtual Student Student { get; set; }

    . . .
}

where, Student is the principal entity and Anamnesis it the entity that shares the PK.

Now I'd like that the relationship created had a Delete Rule = CASCADE. Actually, the relationship that is being created has Delete Rule = NO ACTION as seen in the following picture:

enter image description here

If I manually delete this relation inside the Table Properties window and add other relation with Delete Rule = CASCADE, the code works as I expect allowing me to delete a Student and it's shared Anamnesis that has the same ID.

So, here goes my question:

Is there a way of using Data Annotation (not Fluent API) in my class so that I get a Relation with CASCADE delete rule? I'd prefer using Data Annotation but if it's not possible, I'd be happy with some Fluent API code that makes this work.

NOTE

I have tried the Fluent API code that is shown in this post. It doesn't work in my case where I have bidirectional properties.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following fluent API code perfectly switch on the cascade delete on the database:

public class Student
{   
    public virtual int StudentId { get; set; }
    public virtual Anamnesis Anamnesis { get; set; }
}

public class Anamnesis
{        
    public int AnamnesisId { get; set; }
    public virtual Student Student { get; set; }
}

public class Context : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Anamnesis> Anamnesises { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
                    .HasRequired(s => s.Anamnesis)
                    .WithRequiredPrincipal(a => a.Student)
                    .WillCascadeOnDelete();
    }
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...