Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EF编码第一个参考键作为主键_C#_Entity Framework Core_Entity Framework Migrations - Fatal编程技术网

C# EF编码第一个参考键作为主键

C# EF编码第一个参考键作为主键,c#,entity-framework-core,entity-framework-migrations,C#,Entity Framework Core,Entity Framework Migrations,在这里陷入了非常荒谬的境地 我在EF core、ASP.NET core、Visual Studio 2017社区中编写代码 我有一个没有主键的模型,如: public class LoginRecord { public User User { get; set; } public int UserId { get; set; } public DateTime LastLogin { get; set; } public int LoginCount {

在这里陷入了非常荒谬的境地

我在EF core、ASP.NET core、Visual Studio 2017社区中编写代码

我有一个没有主键的模型,如:

public class LoginRecord
{
    public User User { get; set; }

    public int UserId { get; set; }

    public DateTime LastLogin { get; set; }
    public int LoginCount { get; set; } 
}
其中User是一个表,包含名称、电子邮件等所有字段

当我添加迁移时,会弹出一个错误,提示:

实体类型“LoginRecord”需要定义主键

然后我尝试向UserId字段添加[Key]注释,如下所示:

public class LoginRecord
{
    public User User { get; set; }

    [Key]    
    public int UserId { get; set; }

    public DateTime LastLogin { get; set; }
    public int LoginCount { get; set; } 
}
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; } 
}
但是现在,EF创建了一个名为UserId1的新列,它将成为外键

我需要UserId只是一个引用键,而不需要这个表的主键

可能吗?如果是,请帮忙

试试看:

[ForeignKey("UserId"), Column(Order = 0)]
public int UserId { get; set; }

您应该添加一个主键。 我已经了解到,每个表都应该有一个名为table+id的字段。如果您更喜欢,也可以将其命名为id 所以每一条记录都是独一无二的

因此,我建议您将模型更改为以下内容:

public class LoginRecord
{
    public User User { get; set; }

    [Key]    
    public int UserId { get; set; }

    public DateTime LastLogin { get; set; }
    public int LoginCount { get; set; } 
}
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; } 
}

EF需要每个表都有一个主键,您也需要。您可以尝试使用组合主键。假设UserId+LastLogin+Count,但我不确定它是否有效。只需将loginRecorded添加为主键no-EF,任何正确设计的表都必须有主键。你可能应该把用户和登录记录之间的关系设置为1:1。想解释一下原因吗?我希望这只是我的第一篇专栏文章。。。但不是PKey…当键不是复合键时,Column属性不相关。正如评论中提到的,这里的实际要点是LoginRecord需要一个自己的PK。