Landed up in a quite ridiculous situation here.
I'm coding in EF core, ASP.NET core, Visual Studio 2017 community.
I have a model which does not have a primary key like:
public class LoginRecord
{
public User User { get; set; }
public int UserId { get; set; }
public DateTime LastLogin { get; set; }
public int LoginCount { get; set; }
}
where User
is a table with all the fields like name, email etc.
When I do add-migration
, an error pops up saying:
The entity type 'LoginRecord' requires a primary key to be defined.
Then I tried by adding the [Key]
annotation to the UserId
field like this:
public class LoginRecord
{
public User User { get; set; }
[Key]
public int UserId { get; set; }
public DateTime LastLogin { get; set; }
public int LoginCount { get; set; }
}
but now, EF creates a new column called UserId1
which becomes the foreign key.
I need the UserId
to be just a reference key and don't need a primary key for this table.
Is it possible? If yes please help!
You should add an primary key. I've learned that every table should get a field which is named like the table + id. You could also name it id if you like it more. :) So that every record gets unique.
So I would advice you to change your model to something like this:
public class LoginRecord
{
[Key]
public int LoginRecordID {get; set;}
public User User { get; set; }
public int UserId { get; set; }
public DateTime LastLogin { get; set; }
public int LoginCount { get; set; }
}
Try:
[ForeignKey("UserId"), Column(Order = 0)]
public int UserId { get; set; }
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.