c# - Entity Framework 关系映射中的错误

标签 c# .net entity-framework-6

我得到了以下 EF6 映射

namespace Model
{
    [Serializable]
    [Table("PROVISION")]
    public class Provision
    {
        [Key, Column("ID_PROVISION", Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public virtual long Id { get; set; }

        [Column("ID_PROVISION_TYPE")]
        public virtual int IdProvisionType { get; set; }

        [ForeignKey("IdProvisionType")]
        public virtual ProvisionType ProvisionType { get; set; }
    }

    public class ProvisionType 
    {
        [Key, Column("ID_PROVISION_TYPE", Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    }
}

但是,我收到以下错误:

Provision_ProvisionType_Target_Provision_ProvisionType_Source: the types of all properties in the dependent role of a referential constraint must be the same as the corresponding property types in the principal role. The type of property 'Id' on entity 'Provision' does not match the type of property 'Id' on entity 'ProvisionType' in the referential constraint 'Provision_ProvisionType'.

如您所见,外键和引用的主键是同一类型。问题是它在 EF4 上运行良好,但是当我更新到 EF6 时,我开始收到此错误,并且系统很大并且充满了相同的场景。

编辑:忘了说这是一个 .net 4.0 项目

有人知道解决办法吗?

最佳答案

ID_PROVISION 是主键,所以 ForeignKey 使用 ID_PROVISION 中的 id 对 id ID_PROVISION_TYPE 键(键对键),所以你必须定义相同的类型。

试试这个:

namespace Model
{
    [Serializable]
    [Table("PROVISION")]
    public class Provision
    {
        [Key, Column("ID_PROVISION", Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public virtual long Id { get; set; }

        [Key,Column("ID_PROVISION_TYPE")]
        public virtual int IdProvisionType { get; set; }

        [ForeignKey("IdProvisionType")]
        public virtual ProvisionType ProvisionType { get; set; }
    }

    public class ProvisionType 
    {
        [Key, Column("ID_PROVISION_TYPE", Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    }
}

关于c# - Entity Framework 关系映射中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660643/

相关文章:

c# - 如何在 EF6 中使用临时表

.net - 随着扩展方法的出现,抽象类的吸引力是否降低了?

.NET 对象大小限制

c# - 如何使用 EF6 在 C# 模型中创建多列 "reference"索引(连接索引)

C# 检测用户现在是否使用计算机

c# - 使用 Response.Redirect() 时获取线程中止异常

entity-framework-6 - 使用 Entity Framework 的集群列存储

c# - 在 C# 中执行任何其他操作时表单无响应

c# - ebay API - 从拍卖列表中获取 UPC

c# - 在 ASP、C# 和 CSS 中更改图像大小