c# - EF Core 配置复杂类型
问题描述
我目前正在使用 .NET Core 和 EF Core 学习 C# 来处理数据库。
现在我在配置我的实体时遇到了困难。
我写了以下课程:
public class Customer
{
#region Properties
public Guid CustomerID { get; set; }
...
public Address Address { get; set; }
#endregion
public Customer()
{
Address = new Address();
}
}
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
//Primary Key
builder.HasKey(c => c.CustomerID);
//Complex Types
builder.OwnsOne<Address>("Address");
}
}
public class Employee
{
#region Properties
public Guid EmployeeID { get; set; }
...
public Address Address { get; set; }
#endregion
public Employee()
{
Address = new Address();
}
}
public class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
{
public void Configure(EntityTypeBuilder<Employee> builder)
{
//Primary Key
builder.HasKey(c => c.EmployeeID);
//Complex Types
builder.OwnsOne<Address>("Address");
}
}
public class Address
{
public string Street { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public State State { get; set; }
public Country Country { get; set; }
}
我需要为MaxLength = 50的Address
Fluent API 配置类?Address.Street
Customer
Employee
是否可以同时为两者配置它?还是我需要为每个实体配置它?
谢谢你的帮助!
解决方案
@Gert Arnold的有效答案演示了如何以集中的方式为所有目标实体完成您想要的。
如果您想将信息保留在配置类中,那么您可以在其中定义它(但根据具体情况,它可能有点多余):
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
//Primary Key
builder.HasKey(c => c.CustomerID);
//Complex Types
builder.OwnsOne(e => e.Address)
.Property(e => e.Street)
.HasMaxLength(50);
}
}
public class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
{
public void Configure(EntityTypeBuilder<Employee> builder)
{
//Primary Key
builder.HasKey(c => c.EmployeeID);
//Complex Types
builder.OwnsOne(e => e.Address)
.Property(e => e.Street)
.HasMaxLength(42); // or 50 if you want
}
}
推荐阅读
- python - Python 在函数内部使用 vars()[mystring] 基于另一个变量创建变量失败
- javascript - octokit getLabel 返回 TypeError:callback.bind 不是函数
- angularjs - DOM元素在刷新angularjs时消失
- python - 验证文件是否存在于 Tensorflow 流中。使用 tf.gfile.Exists 和字符串张量作为输入
- asp.net-core - 如何在 Scrutor 类似的 StructureMap 中注册程序集上的所有接口
- angular - Angular 6 如何在延迟加载的模块中初始化辅助路由
- spring-boot - SOAP 请求由两个 XSD 模式组成
- java - 引起:org.hibernate.MappingException:无法确定类型:
- android - Firebase UI - custom SnapshotParser is skipped by compiler
- shell - 在 Jenkins 中使用 nohup 时服务器无法上网