我最近在 .NET Core 3.1 中创建了一个 Web API 项目,并使用代码优先方法实现了 Entity Framework Core 。我的每个模型都像这样引用其他模型:
public class Condominium
{
public int Id { get; set; }
public Address Address { get; set; }
public int Levels { get; set; }
public string Description { get; set; }
public CondominiumType CondominiumType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
正如你在这个例子中看到的,我指的是 Address 和 CondominiumType 而不使用引用 Id。迁移数据库时,Entity Framework 将创建相应的外键。
当我必须添加带有新地址的新公寓时,这非常有效,但是当我想添加现有地址或公寓类型时遇到问题。
当我将一个对象传递给具有已添加到数据库中的 ID 的上下文时,程序会抛出异常,因为我违反了表的 UNIQUE 约束。我知道我可以通过添加类似这样的引用键来解决这个问题
public class Condominium
{
public int Id { get; set; …Run Code Online (Sandbox Code Playgroud)