我首先使用代码在我的类之间创建关系。集成是通过 MySql 进行的,但是,迁移后,当我检查工作台 ERD 时,将其视为一对多关系。
如何使用下面提到的类建立一对一的关系?
这是我的代码:
public class About
{
[ForeignKey("User")]
public int Userid { get; set; }
public int id { get; set; }
public string about_file { get; set; }
public string about_desc { get; set; }
public virtual User User { get; set; }
}
public class User
{
[Key]
public int id { get; set; }
public string login { get; set; }
public string password { get; set; }
public virtual About About { get; set; }
public ICollection<Offers> Offers { get; set; } = new List<Offers>();
public ICollection<Portfolio> Portifolios { get; set; } = new List<Portfolio>();
}
Microsoft.EntityFrameworkCore 版本:{5.0.7}
最佳答案
这只是按照惯例的一对一关系。从 Entity Framework 的角度来看,使用导航属性而不是集合可确保只有一个子实体可以与一个父实体相关。但在数据库级别,没有什么可以阻止创建多个子实体。
如果您想在数据库级别强制执行它,请向子实体上的外键添加 UNIQUE 约束,或者使两个实体上的主键相同并将其设为外键。
关于c# - Entity Framework 和.NET 的一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68411673/