Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

c# - How to get Entity Framework Code First and nullable foreign key properties to work?

I'm trying to create a simple entity framework code first application. I have these classes:

public class User
{
    public int UserId { get; set; }

    public string Username { get; set; }

    public virtual ActivationTicket ActivationTicket { get; set; }
}

public class ActivationTicket
{
    public int ActivationTicketId { get; set; }

    public virtual User User { get; set; }

    public string Ticket { get; set; }
}

When I try to create a new user and save it to the database (a user without a ActivationTicket that is) I receive an exception

The INSERT statement conflicted with the FOREIGN KEY constraint "ActivationTicket_User". The conflict occurred in database "Test", table "dbo.ActivatioTickets", column 'ActivationTicketId'. The statement has been terminated.

I assume EF treats the mapping between User and ActivationTicket as 1-1 but it should be 1-0..1

What do I have to do to get this to work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need a mapping rule like this:

modelBuilder
    .Entity<User>()
    .HasOptional<ActivationTicket>(u => u.ActivationTicket)
    .WithOptionalPrincipal();

This will give you an ActivationTickets table with a UserId that is nullable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...