我有一个成员模型,其地址为一对一样式,其中地址行只能属于一个成员。我正在试图找出如何定义这个,以便当我删除一个成员时,会员拥有的地址和地址被级联删除。
public class Member
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("Address")]
public int AddressId { get; set; }
public virtual Address Address { get; set; }
}
我也有地址
public class Address : IEntity
{
[Key]
public int Id { get; set; }
....
}
我已尝试以下方法获取级联删除地址
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Entity<Member>()
.HasRequired(m => m.Address)
.WithRequiredDependent()
.WillCascadeOnDelete(true);
}
和
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Entity<Member>()
.HasRequired(m => m.Address)
.WithRequiredPrinciple()
.WillCascadeOnDelete(true);
}
有人可以帮助我走上正轨吗?迁移失败的行如下。
System.Data.Entity.ModelConfiguration.ModelValidationException: One
or more validation errors were detected during model generation:
System.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid
in Role 'Member_Address_Source' in relationship 'Member_Address'. Because the
Dependent Role properties are not the key properties, the upper bound of the
multiplicity of the Dependent Role must be '*'.
从docs找到这个 - 一对一只有一个导航属性
modelBuilder.Entity<OfficeAssignment>()
.HasKey(t => t.InstructorID);
modelBuilder.Entity<Instructor>()
.HasRequired(t => t.OfficeAssignment)
.WithRequiredPrincipal();
如果我有机会,我会发布它是否有效
答案 0 :(得分:0)
你的逻辑颠倒了。你现在写的是每个成员都有一个地址,这导致一个地址可以存在于几个成员的事实,这意味着在层次结构表中,地址在成员之上。删除子项不会导致删除父项。
尝试删除地址,如果你想测试我刚写的内容,你的会员就会消失。
为了你的逻辑工作,你需要写:
public class Member
{
[Key]
public int Id { get; set; }
...
}
public class Address : IEntity
{
[Key]
public int Id { get; set; }
public int MemberId {get;set;}
public virtual Member Member {get;set;}
....
}
如果启用级联删除和删除成员,地址也将被删除。
编辑:
如果你正在寻找一对一的关系,那就是这样:
public class Member
{
[Key]
public int Id {get;set;}
...
public virtual Address Address {get;set;}
}
public class Address
{
[ForeignKey("Member")]
public int Id {get;set;}
...
public virtual Member Member {get;set;}
}
答案 1 :(得分:0)
我尝试了一些不同的东西,但这是EF创建一对一映射的方式,只在关系的一侧有导航..
public class Member
{
[Key]
public int Id { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
[Key]
public int MemberId {get;set;}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Entity<Address>()
.HasKey(t => t.MemberID);
modelBuilder
.Entity<Member>()
.HasRequired(t => t.Address)
.WithRequiredPrincipal();
}
执行此操作可使级联删除正常工作,以便在删除成员时删除地址。