目前,我的实体使用如下模型:
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual User User { get; set; }
}
这很好用,但我一直看到 CodeFirst 示例,其中为模型中的外部实体显式创建了 Id 属性。这是有道理的,所以我不必延迟加载用户来检索与MyModel
实例关联的用户的 id 值。
但是,当我更改MyModel
为:
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual int UserId { get; set; }
public virtual User User { get; set; }
}
尝试提交MyModel
实例时出现以下异常:
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "MyModel_User". The conflict occurred in database "mjlunittest", table "dbo.Users", column 'Id'.
为什么我会收到此异常?