I have two tables and want to use PK of one of them in another one as 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 Student table uses User's primary key.
How can I implement this with Fluent API?
(As a second question, if I delete a value from Student table, will accur a cascade delete?)
How can I implement this with Fluent API?
modelBuilder.Entity<Student>()
.HasRequired(s => s.User)
.WithOptional();
if I delete a value from Student table, will accur a cascade delete.
No, because Student is the dependent in the relationship (it carries the foreign key) and not the principal (which is User). Cascading delete is only in effect if you delete the principal. For a one-to-one relationship you have to enable it manually though:
modelBuilder.Entity<Student>()
.HasRequired(s => s.User)
.WithOptional()
.WillCascadeOnDelete(true);
Now, if a User gets deleted the related Student (if there is any) will be deleted as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With