简体   繁体   English

唯一索引属性的实体框架FK

[英]Entity Framework FK on Unique Index Property

I`d like to add foreign key on unique not null attribute in second table. 我想在第二张表的唯一非null属性上添加外键。 Here how it look like: 这里看起来像:

 public class T_AlarmTresholds
    {
        [Key]
        public int Id { get; set; }
              ....
              ....                
        public Guid MeasurementGuid { get; set; }

        [ForeignKey("MeasurementGuid")]
        public virtual T_Measurements Measurement { get; set; }
    }


 public partial class T_Measurements
    {
        public int Id { get; set; }
        [Index("UC_Guid", IsUnique = true)]
        public Guid GUID { get; set; }
    }

Here is model builder: 这是模型构建器:

modelBuilder.Entity<T_Measurements>()
                .HasMany(x => x.T_AlarmTresholds)
                .WithRequired(x => x.Measurement)
                .HasForeignKey(x => x.MeasurementGuid);

Entity framework throws error while SQL Server accept this solution. 当SQL Server接受此解决方案时,实体框架会引发错误。 Here is error in Visual Studio while debugging: 这是调试时Visual Studio中的错误:

{"One or more validation errors were detected during model generation:\\r\\n\\r\\nT_Measurements_T_AlarmTresholds_Source_T_Measurements_T_AlarmTresholds_Target: : 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 'MeasurementGuid' on entity 'T_AlarmTresholds' does not match the type of property 'ID' on entity 'T_Measurements' in the referential constraint 'T_Measurements_T_AlarmTresholds'.\\r\\n"} {“在模型生成期间检测到一个或多个验证错误:\\ r \\ n \\ r \\ nT_Measurements_T_AlarmTresholds_Source_T_Measurements_T_AlarmTresholds_Target ::引用约束的从属角色中的所有属性的类型必须与主体角色中的相应属性类型相同。实体'T_AlarmTresholds'上的属性'MeasurementGuid'的类型与参照约束'T_Measurements_T_AlarmTresholds'中实体'T_Measurements'的属性'ID'的类型不匹配。\\ r \\ n“}

You don't put the foreign key on the virtual object itself you need to create a new property in T_AlarmTresholds: 您无需将外键放在虚拟对象本身上,而无需在T_AlarmTresholds中创建新属性:

public int T_MeasurementsId{get; set;}

to act as the foreign key. 充当外键。 The dependency property (the virtual one) will then link up automatically. 然后,依赖项属性(虚拟属性)将自动链接。 You also need to remove the ForiegnKey attribute from the virtual property. 您还需要从虚拟属性中删除ForiegnKey属性。


Edit: Just spotted that your code doesn't use the Id column as the primary key but instead uses the Guid, so you'll instead want to add the foreign key attribute to the MeasurementGuid property. 编辑:刚刚发现您的代码不使用Id列作为主键,而是使用Guid,因此您想将外键属性添加到MeasurementGuid属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM