c# - 在 EF6 中使用枚举作为 FK

标签 c# entity-framework entity-framework-6

我们有一个枚举 Supplier

但现在我们还需要有一些关于该关系的域数据

因此,在域代码的 99.9% 中,我们对枚举进行操作,如 product.Supplier == Suppliers.FedEx

但现在我们还添加了 product.SupplierInfo.CanAdjustPickupTime,其中 SupplierInfo 是一个实体,而不仅仅是一个简单的枚举类型。

我试过这些配置

Property(p => p.Supplier)
    .IsRequired()
    .HasColumnName("SupplierId");

HasRequired(p => p.SupplierInfo)
    .WithMany()
    .HasForeignKey(p => p.Supplier); //I have also tried casting to int doing .HasForeignKey(p => (int)p.Supplier)

这将失败

The ResultType of the specified expression is not compatible with the required type. The expression ResultType is 'MyApp.Model.Suppliers' but the required type is 'Edm.Int32'. Parameter name: keyValues[0]

也试过

Property(l => l.Supplier)
    .IsRequired()
    .HasColumnName("SupplierId");

HasRequired(p => p.SupplierInfo)
    .WithMany()
    .Map(m => m.MapKey("SupplierId"));

这当然会给旧的好东西

One or more validation errors were detected during model generation:

SupplierId: Name: Each property name in a type must be unique. Property name 'SupplierId' is already defined.

我当然可以将 SupplierId 定义为属性,将其与 HasForeignKey 一起使用,但随后我需要更改为 .SuppliedId == (int)Suppliers.FedEx 等。不是真的一个办法。

我还可以添加一个使用 SupplierId 属性作为支持字段的属性枚举,但这不适用于表达式,因为它需要使用真正的映射数据库属性

有什么想法吗?

最佳答案

我有课:

public class Agreement
{
    public int Id { get; set; }
    public AgreementStateTypeEnum AgreementStateId { get; set; }
}

public class AgreementState
{
    public int Id { get; set; }
    public string Title { get; set; }
}

上下文:

 public class AgreementContext :DbContext
 {
     public AgreementContext() : base("SqlConnection") { }
     public DbSet<Agreement> Agreements { get; set; }
 }

在方法OnModelCreating 中我什么也没写。 我的枚举:

 public enum AgreementStateTypeEnum : int
 {
        InReviewing = 1,
        Confirmed = 2,
        Rejected = 3 
 }

在数据库中:在表 Agreements 中我有外键 AgreementStateId - 它是表 AgreementStates 的链接。 一切正常。例如:

var temp = context.Agreements.First(x => x.AgreementStateId == AgreementStateTypeEnum.Confirmed);

我如何使用枚举外键。

关于c# - 在 EF6 中使用枚举作为 FK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32861270/

相关文章:

entity-framework - Breeze 中的多对多关系

entity-framework - 通过 Entity Framework 来自存储过程的标量值

c# - denyandaddcustomizedpages - 使用 csom 为现代团队网站修改属性

C# 数据库 ConnectionString 属性尚未初始化

c# - Entity Framework 删除问题(使用wpf)

entity-framework - Entity Framework 6 Code first 覆盖 MigrationCodeGenerator 的默认值

MySQL 版本 7.0.6-IR3 尝试连接数据库时出现问题

c# - 防止数据网格在 C# 中加载 Entity Framework 导航属性

c# - 使用 Entity Framework 查询 SQL 表

c# - 从布局页面访问 session 变量 ASP.NET MVC3 RAZOR