首页 > 解决方案 > 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的AddressFluent API 配置类?Address.StreetCustomerEmployee

是否可以同时为两者配置它?还是我需要为每个实体配置它?

谢谢你的帮助!

标签: c#entity-framework-core

解决方案


@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
    }
}

推荐阅读