【发布时间】:2011-08-05 20:14:53
【问题描述】:
我有一个 User Country 模型。一个用户属于一个国家,但可能不属于任何一个(空外键)。
如何设置?当我尝试插入一个国家为空的用户时,它告诉我它不能为空。
型号如下:
public class User{
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class Country{
public List<User> Users {get; set;}
public int CountryId {get; set;}
}
错误:A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}
【问题讨论】:
-
如果我错了,请您纠正我。在 code first asp.net mvc - 5 entity framework 中,外键默认为 NULLABLE。
-
如果我们想让它不可为空。如果没有,我们需要使用流利的 api,然后使用“必需”属性进行装饰。我说的对吗?
-
如果我们都不这样做,那么外键将默认为 Nullable
标签: entity-framework mapping ef-code-first foreign-key-relationship entity-framework-4.1