级联删除规则EF 4.1代码首先使用共享主键关联 [英] Cascade Delete Rule in EF 4.1 Code First when using Shared Primary Key Association
问题描述
我根据这个答案实施了双向1:1的关系:
。
以下流畅的API代码完美地打开级联删除在数据库上:
public class Student
{
public virtual int StudentId {get;组; }
public virtual Anamnesis Anamnesis {get;组;
}
public class Anamnesis
{
public int AnamnesisId {get;组; }
public virtual Student Student {get;组; }
}
public class上下文:DbContext
{
public DbSet< Student>学生{get;组; }
public DbSet< Anamnesis>消失组;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity< Student>()
.HasRequired(s => s.Anamnesis)
.WithRequiredPrincipal(a => a.Student)
.WillCascadeOnDelete();
}
}
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:
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.
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();
}
}
这篇关于级联删除规则EF 4.1代码首先使用共享主键关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!