Entity Framework: how to implement a shared primary key with Fluent API?
I have two tables and want to use the PK of one of them in the other like PK.
This is my implementation with data annotation:
public class User
{
public System.Guid UserId { get; set; }
public string UserName { get; set; }
}
public class Student
{
[Key, ForeignKey("User")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public System.Guid StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// shared primary key
public virtual User User { get; set; }
}
Here the table is Student
using the primary key User
.
How can I implement this with the Fluent API?
(As a second question, if I delete a value from the table Student
, will the cascading delete be deleted?)
source to share
How can I implement this using the Fluent API?
modelBuilder.Entity<Student>()
.HasRequired(s => s.User)
.WithOptional();
if i remove the value from the Student table there is exactly a cascading delete.
No, because it Student
is relationship dependent (it carries a foreign key), not a primary one (i.e. User
). A cascading deletion only takes effect if the principal is deleted. For a one-to-one relationship, you have to enable it manually, but:
modelBuilder.Entity<Student>()
.HasRequired(s => s.User)
.WithOptional()
.WillCascadeOnDelete(true);
Now, if a User
is removed, the related Student
(if any) will also be removed.
source to share