我们有一个枚举 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/