0

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.

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 :

modelBuilder.Entity<Customer>()
            .HasMany(e => e.Orders)
            .WithRequired(e => e.Customer)
            .WillCascadeOnDelete(false);
3
  • 3
    You need to make the CustomerID property nullable: public int? CustomerID { get; set; } Commented Feb 26, 2017 at 7:33
  • 1
    Could you clarify your questions, as I don't understand "A user belongs to a country, but may not belong to any (null foreign key)". What does that mean to you? What does it have to do with the Order class you present? Please be a bit more precise with your question. Optionally, from what I can observe you can try to make the CustomerID property nullable. (edit: just like @Felipe Cruze just mentioned above :)) Commented Feb 26, 2017 at 7:34
  • 1
    You are talking about problems with user and country but the code deals with customer and order. Did not make sense to me Commented Feb 26, 2017 at 8:27

1 Answer 1

1

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 { get; set; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.