如何获得实体框架code第一,可为空的外键属性的工作?为空、如何获得、实体、框架

由网友(輕描)分享简介:我想创建一个简单的实体框架code首次应用。我有这些类:I'm trying to create a simple entity framework code first application. I have these classes:public class User{public int UserId {...

我想创建一个简单的实体框架code首次应用。我有这些类:

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

当我尝试创建一个新用户,并将其保存到数据库(用户没有Activati​​onTicket这是)我收到一个异常

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

INSERT语句冲突与外键约束Activati​​onTicket_User。发生在数据库中的测试,表dbo.Activati​​oTickets,列Activati​​onTicketId的冲突。该语句已终止。

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.

我想EF对待用户和Activati​​onTicket之间的映射为1-1,但它应该是1-0..1

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?

推荐答案

您将需要一个像这样的映射规则:

You will need a mapping rule like this:


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

这会给你一个Activati​​onTickets表用户ID是空。

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

阅读全文

相关推荐

最新文章