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

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

问题描述

我有一个用户 国家/地区模型。用户属于国家/地区,但可能不属于任何(空外键)。

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天全站免登陆