下面是我的课程
class Company
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public int? CityId { get; set; }
public City City { get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
我的问题是:
我可以将地址类设置为OwnedType,因为城市ID是可选的
如果我将“地址”设置为拥有类型,那么我的城市类别也需要拥有类型吗?
预先感谢a。使用ef core 3.1
答案 0 :(得分:1)
您可以像这样将Address
类设为OwnedType。
地址类:
public class Address
{
public string Street { get; set; }
public int? CityId { get; set; }
public City City { get; set; }
public Company Company { get; set; }
}
公司类别:
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
Fluent Api:
public class YourDbContext : DbContext
{
public YourDbContext (DbContextOptions<YourDbContext> options)
: base(options)
{
}
//Note:no need add Address DbSet
public DbSet<City> City { get; set; }
public DbSet<Company> Company { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>().OwnsOne(c => c.Address);
}
}
如果我将地址设置为拥有类型,那么我的城市班级也需要拥有类型吗?
您的城市班级不需要是拥有者类型。
参考:
https://docs.microsoft.com/en-us/ef/core/modeling/owned-entities#explicit-configuration
结果:
配置拥有的类型时,此company
和address
会生成一个表,并且可以设置城市ID。如果要设置城市ID,则需要插入city
表中的新记录。