我已经提供了一个数据库,我需要为其设置Code First。我想我大部分都是完成的,现在我遇到的问题是我想改变实体中的一些外键名字,使其更有意义。
I have been supplied a DB, and I need to get Code First set up for it. I think I'm mostly done, the problem that I'm running into right now is I want to change some of the foreign key names in the entities to make a little more sense.
假设我有两个表格:Person和Location,如下所示:
Let's say I have two tables, Person and Location, that look like this:
Person ------ PersonId int not null (PK) DefaultLocation int not null (FK) Location -------- LocationId int not null (PK)对于位置实体,我想我已经得到它:
For the location entity, I think I've got it:
public class Location { [Key] public int LocationId { get; set; } [InverseProperty("DefaultLocation")] public List<Person> PeopleWithDefault { get; set; } }现在,我想要的是在我的Person实体上拥有2个属性,一个DefaultLocation导航属性和一个DefaultLocationId属性的外键。这是我现在所在的地方:
Now, what I want is to have 2 properties on my Person entity, a DefaultLocation navigation property, and a DefaultLocationId property for the foreign key. This is where I'm at right now:
public class Person { [Key] public int PersonId { get; set; } [ForeignKey("Location")] [Column("DefaultLocation")] [Required] public int DefaultLocationId { get; set; } public virtual Location DefaultLocation { get; set; } }哪个是扔这个坏男孩:
Person类型上的属性DefaultLocationId的ForeignKeyAttribute无效。在依赖类型Person上找不到导航属性Location。名称值应该是一个有效的导航属性名称。
The ForeignKeyAttribute on property 'DefaultLocationId' on type 'Person' is not valid. The navigation property 'Location' was not found on the dependent type 'Person'. The Name value should be a valid navigation property name.
所以,这个错误是完全正确的...我只是不知道如何要解决这个问题。我显然在某处丢失了一个注释,或者使用[ForeignKey]不正确。任何人都可以帮助我吗?
So, that error makes perfect sense... I just have no idea how to fix it. I'm obviously missing an annotation somewhere, or using [ForeignKey] incorrectly. Can anyone help me out?
推荐答案将FK属性中的字符串更改为属性的名称,而不是名称键入: [ForeignKey(DefaultLocation)]
Change the string in the FK attribute to the name of the property, not the name of the type: [ForeignKey("DefaultLocation")]
更多推荐
在Code First中无法获取使用外键的属性名称
发布评论