简体   繁体   English

实体框架上的ForeignKey属性

[英]ForeignKey attribute on Entity Framework

Let's suppose i've a class Auction 假设我上课拍卖

public class Auction {
[Key]
public int Id { get; set;}

public User Seller {get; set;}
public User Winner {get; set;}
}

and a class User 和一个班级用户

public class User {

[Key]
public string Username {get;set;}
public string Password {get; set;}
}

What can i do to make Seller and Winner as FK using ForeignKey attribute on Visual Studio? 使用Visual Studio上的ForeignKey属性,如何使卖方和获胜者成为FK?

Edit 编辑

I use the [key] attribute because i've got other tables in the db and their PK is not called id, so i use in every class the attribute [key] to use the same style. 我使用[key]属性是因为我在数据库中有其他表,并且它们的PK不称为id,因此我在每个类中都使用[key]属性来使用相同的样式。

And when i try to upload a Seller of an Auction by using an already existing user it says 当我尝试通过使用现有用户上传拍卖的卖家时,它说

The ForeignKeyAttribute on property 'Seller' on type 'Database.Auction' is not valid. The foreign key name 'User' was not found on the dependent type 'Database.Auction'. The Name value should be a comma separated list of foreign key property names.

It was for this reason i wanted to specify the FK 正是由于这个原因,我想指定FK

They already are FK in your Auction class. 他们已经是您Auction课上的FK。 They will be mapped as FK. 它们将被映射为FK。 You might want to use lazy loading later on so: 您以后可能要使用延迟加载:

public class Auction {
   public int Id { get; set;}

   public virtual User Seller {get; set;}
   public virtual User Winner {get; set;}
}

Also you don't need the [Key] annotation above property called Id . 同样,您也不需要[Key] Id [Key]上面的名为Id属性。

Update after question was edited: 问题编辑后更新:

You might need to enable migrations. 您可能需要启用迁移。 Go to the Package Manager Console, if it is not open you can open it via menu View at the menu bar of the Visual Studio. 转到“程序包管理器控制台”,如果尚未打开,则可以通过Visual Studio菜单栏中的“视图”将其打开。

Then write in it enable-migrations enter, then set AutomaticMigrations in the generated class to true , then again in Package Manager console write update-database , run your application. 然后在其中写入enable-migrations输入,然后将生成的类中的AutomaticMigrations设置为true ,然后再次在Package Manager控制台中写入update-database ,运行您的应用程序。

Foot notes: 脚注:

You didn't state what kind of app your are creating but usually keeping user password is a bad idea. 您没有说明要创建哪种类型的应用程序,但通常保留用户密码是一个坏主意。 You usually suppose to keep hashed version of it. 您通常会假设保留其散列版本。

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

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