简体   繁体   中英

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?

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.

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

They already are FK in your Auction class. They will be mapped as 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 .

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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