在Code First中无法获取使用外键的属性名称

编程入门 行业动态 更新时间:2024-10-25 21:28:56
本文介绍了在Code First中无法获取使用外键的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经提供了一个数据库,我需要为其设置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中无法获取使用外键的属性名称

本文发布于:2023-11-12 00:59:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580052.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   名称   Code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!