简体   繁体   English

如何在Entity Framework代码优先中设置空外键

[英]How to set null foreign key in Entity Framework code-first

I have a Order < Customer model. 我有一个订单<客户模型。

How do I set this up? 我该如何设置? When I try to insert a user with a null customerid, it tells me that it cannot be null. 当我尝试插入一个客户ID为空的用户时,它告诉我不能为空。

The model is as follows: 该模型如下:

public class Order
{
    public long OrderID { get; set; }
    public int CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}

public partial class Customer
{
    public int CustomerID { get; set; }   
}

In DbContext : DbContext

modelBuilder.Entity<Customer>()
            .HasMany(e => e.Orders)
            .WithRequired(e => e.Customer)
            .WillCascadeOnDelete(false);

Have you tried to replace line 您是否尝试过更换线

.WithRequired(e => e.Customer)

with

.WithOptional(e => e.Customer)

?

And I make the CustomerID property nullable: public int? 我将CustomerID属性设置为可空:public int? CustomerID { get; 客户ID {get; set; 组; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用代码优先的实体框架指定外键 - How to specify a foreign key with code-first Entity Framework 实体框架代码优先设置的外键和同一表中的主键 - Entity Framework code-first set foreign key with primary key in same table 更新实体框架4.1代码优先中的外键关联 - Updating Foreign key associations in Entity Framework 4.1 Code-First 实体框架代码优先的多对多表外键 - Entity Framework code-first foreign key to many to many table Oracle上的实体框架外键问题-代码优先 - Entity Framework foreign key problems on Oracle - code-first 代码优先实体框架:外键 - 无效的对象名称 - Code-first Entity Framework : foreign key - invalid object name 实体框架代码优先外键 - Entity Framework code-first foreign keys 更正注释以在Entity Framework代码优先中设置主键 - Correct annotation to set primary key in Entity Framework code-first 具有可选链接实体的实体框架核心代码优先外键 - Entity Framework Core code-first foreign key with optional linked entity 在Code-First Entity Framework中包含复合主键中的外键 - Include foreign key in composite primary key in Code-First Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM