I want to implement a unidirectional one to one relationship; however on cascade delete doesn't work.
I have the following classes:
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
}
In my Context class, I'm mapping the relationship like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasRequired(s => s.Address)
.WithOptional()
.Map(m => m.MapKey("Address_Id"))
.WillCascadeOnDelete();
}
For some reason, it's not deleting the address
when, student
object is deleted.
Moreover, I also want to add the foreign key property (i.e. AddressId
) in the Student
class like this:
[ForeignKey("Address")]
[Column("Address_Id")]
public string AddressId { get; set; }
However, I get this error when I try to add a new migration:
Address_Id: Name: Each property name in a type must be unique. Property name 'Address_Id' is already defined.
I do believe I'm mixing things up (with MapKey
and the attributes of AddressId
). However, I don't know how to fix this.
I went through this SO question and this article; however, no luck so far.
Link to DotNetFiddle. It won't work cause there is no database.