我希望实现一对一的单向关系,但是级联删除不起作用。
我有以下类:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
//I don't want the StudentId foreign key or the property of Student class here
}
在我的Context类中,我将关系映射如下:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasRequired(s => s.Address)
.WithOptional()
.Map(m => m.MapKey("Address_Id"))
.WillCascadeOnDelete();
}
由于某些原因,当删除student
对象时,它没有删除address
。
此外,我还想在Student
类中添加外键属性(即AddressId
):
[ForeignKey("Address")]
[Column("Address_Id")]
public string AddressId { get; set; }
然而,当我尝试添加新的迁移时,出现以下错误:
Address_Id: Name: Each property name in a type must be unique. Property name 'Address_Id' is already defined.
我相信我正在混淆(使用MapKey
和AddressId
属性)。然而,我不知道该如何解决这个问题。
链接到DotNetFiddle。它不会工作,因为没有数据库。