在代码中,我有一个如下所示的对象图:
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Publisher
{
public int PublisherId { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string Postcode { get; set; }
}
如何在关系数据库模式中对此进行建模?
这需要是0-1..1关系,即作者和出版商可能有或没有地址。
理想情况下,地址必须由作者或发布者引用,但不能同时引用。
如果您可以使用导航属性在Entity Framework Core中对其进行建模,并且在删除作者或发布者时使用级联删除删除地址,则会获得巨大的奖励。 (但我打赌没有人能够)。
我列出了我尝试过的所有内容,但帖子会很长,没有人会阅读它。只是说我已经尝试了我能想到的一切,这会更快。
答案 0 :(得分:4)
有很多方法可以实现EF Core的目标。关键点是Address
将是关系的依赖结束,并且它将可选 FK包含到主体实体{ {1}}和Author
。
以下是可能的Publisher
模型和配置:
(1)Address
具有明确的FK和导航属性
型号:
Address
配置:
public class Address
{
public int AddressId { get; set; }
public string Postcode { get; set; }
public int? AuthorId { get; set; }
public Author Author { get; set; }
public int? PublisherId { get; set; }
public Publisher Publisher { get; set; }
}
(2)modelBuilder.Entity<Author>()
.HasOne(e => e.Address)
.WithOne(e => e.Author)
.HasForeignKey<Address>(e => e.AuthorId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Publisher>()
.HasOne(e => e.Address)
.WithOne(e => e.Publisher)
.HasForeignKey<Address>(e => e.PublisherId)
.OnDelete(DeleteBehavior.Cascade);
仅包含导航属性
型号:
Address
配置:
public class Address
{
public int AddressId { get; set; }
public string Postcode { get; set; }
public Author Author { get; set; }
public Publisher Publisher { get; set; }
}
(3)modelBuilder.Entity<Author>()
.HasOne(e => e.Address)
.WithOne(e => e.Author)
.HasForeignKey<Address>("AuthorId")
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Publisher>()
.HasOne(e => e.Address)
.WithOne(e => e.Publisher)
.HasForeignKey<Address>("PublisherId")
.OnDelete(DeleteBehavior.Cascade);
仅具有明确的FK属性
型号:
Address
配置:
public class Address
{
public int AddressId { get; set; }
public string Postcode { get; set; }
public int? AuthorId { get; set; }
public int? PublisherId { get; set; }
}
(4)modelBuilder.Entity<Author>()
.HasOne(e => e.Address)
.WithOne()
.HasForeignKey<Address>(e => e.AuthorId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Publisher>()
.HasOne(e => e.Address)
.WithOne()
.HasForeignKey<Address>(e => e.PublisherId)
.OnDelete(DeleteBehavior.Cascade);
没有明确的FK和导航属性
型号:
Address
配置:
public class Address
{
public int AddressId { get; set; }
public string Postcode { get; set; }
}