c# - 如何提取 EF6 Code First 中的部分属性配置以重复使用多次?

标签 c# entity-framework-6 ef-code-first-mapping

要在 EF6 Code First 中映射列,我们使用以下代码:

Property(o => o.Email).HasColumnType("varchar").HasMaxLength(255).IsRequired();

为了防止为所有电子邮件列多次写入“.HasColumnType("varchar").HasMaxLength(255)”(例如),我想将其分解并定义一个每次我都可以使用的电子邮件配置需要。我想这样做:

Property(o => o.Email).IsEmailColumn(EMail).IsRequired();

我怎样才能做到这一点?

谢谢。

最佳答案

您可以将通用代码放入自定义的“流畅”扩展方法中,如下所示:

using System.Data.Entity.ModelConfiguration.Configuration;

public static partial class ConfigurationExtensions
{
    public static StringPropertyConfiguration IsEmailColumn(this StringPropertyConfiguration property)
    {
        return property.HasColumnType("varchar").HasMaxLength(255);
    }
}

它允许您使用

Property(o => o.Email).IsEmailColumn().IsRequired();

关于c# - 如何提取 EF6 Code First 中的部分属性配置以重复使用多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48718754/

相关文章:

c# - IEnumerable 在与 namespace System.Collections 一起使用时报告编译器错误

linq - 使用 linq to entities (EF) 忽略搜索重音

c# - Entity Framework 代码首先使用导航属性一个Key

c# - Entity Framework - 一对一 - ReferentialConstraint 映射到存储生成的列

c# - 可以查询 NotMapped 属性吗?

entity-framework - 如何使 Entity Framework Core 创建不强制执行的外键约束

c# - 如果存在无效的属性值,Asp.net core 不会绑定(bind) post 模型

c# - 如何最好地执行从父类(super class)到子类的成员分配?

c# - 使用BackgroundWorker先后完成两个方法WPF/C#