实体框架代码优先空外键 [英] Entity framework code-first null foreign key

本文介绍了实体框架代码优先空外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User <国家模型.一个用户属于一个国家,但可能不属于任何(空外键).

I have a User < Country model. A user belongs to a country, but may not belong to any (null foreign key).

我该如何设置?当我尝试插入一个国家为空的用户时,它告诉我它不能为空.

How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.

模型如下:

 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;}
}

错误:无法插入外键值,因为对应的主键值不存在.[ 外键约束名称 = Country_Users ]"}

推荐答案

你必须让你的外键可以为空:

You must make your foreign key nullable:

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    public virtual Country Country { get; set; }
}

这篇关于实体框架代码优先空外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆