'Entity Framework - Foreign keys and Navigation Properties
I need your help understanding relationships between tables. I´m having a hard time trying to understand the usage/need of using navigation properties with foreign key properties to define relantionships. Given the 2 classes below,
public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public string Name{ get; set; }
}
public class Package
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public Guid AccountId { get; set; }
public virtual Person Account { get; set; }
public Guid ShipperId { get; set; }
public virtual Client Shipper { get; set; }
[Required]
public Guid ReceiverId { get; set; }
public virtual Client Receiver { get; set; }
}
If I try to update the database, I get the error
Introducing FOREIGN KEY constraint 'FK_' on table 'Packages' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
On the other hand if I remove the property public Guid ....Id { get; set; }, the database is created with the foreign keys but the [Required] annotation as no effect.
What´s the difference between including a Guid property and not?
Solution 1:[1]
try to use this classes:
public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public string Name{ get; set; }
[InverseProperty(nameof(Package.Account))]
public virtual ICollection<Package> Packages { get; set; }
}
public class Package
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public Guid AccountId { get; set; }
[ForeignKey(nameof(AccountId))]
[InverseProperty("Packages")]
public virtual Person Account { get; set; }
}
and use this code in dbcontext:
modelBuilder.Entity<Package>(entity =>
{
entity.HasOne(d => d.Person)
.WithMany(p => p.Packages)
.HasForeignKey(d => d.AccountId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |
