EF尝试将外键值插入主键字段

时间:2014-03-06 18:32:12

标签: entity-framework code-first

我定义了以下两个实体。 ResponseSeries可以有相关的TabletUserSession。这是一个相当直接的一对一或零关系。

public class ResponseSeries : TrackedEntity
{
    public ResponseSeries()
    {
        Responses = new Collection<Response>();
    }
    public Int32 ResponseSeriesId { get; set; }

    public virtual TabletUserSession TabletUserSession { get; set; }
    public virtual ICollection<Response> Responses { get; set; }

}

public class TabletUserSession : TrackedEntity
{
    public Int32 TabletUserSessionId { get; set; }
    public Int32 ResponseSeriesId { get; set; }
    public Int32? TabletId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime? ClosedDate { get; set; }

    public virtual Tablet Tablet { get; set; }
    public virtual ResponseSeries ResponseSeries { get; set; }
}

我像这样配置映射:

public TabletUserSessionMap()
{
    HasRequired(tus => tus.ResponseSeries).WithOptional(rs => rs.TabletUserSession);
}

当我尝试为此创建新的ResponseSeries和新的TabletUserSession时:

responseSeries.TabletUserSession = new TabletUserSession
{
    StartDate = DateTime.Now,
    TabletId = request.TabletId,
};

context.ResponseSeries.Add(responseSeries);
context.SaveChanges();

插入TabletUserSession时会引发错误,因为EF会尝试将ResponseSeriesId插入TabletUserSessionId

INSERT [dbo].[TabletUserSession]
       ([TabletUserSessionId],
        [ResponseSeriesId],
        [TabletId],
        [StartDate],
        [ClosedDate],
        [Version],
        [CreatedUserId],
        [CreatedDate],
        [LastUpdateUserId],
        [LastUpdateDate])
VALUES (4404 /* @0 */, -- <--This is going into the wrong field!
        0 /* @1 */,
        9 /* @2 */,
        '2014-03-06T13:30:03' /* @3 */,
        NULL,
        1 /* @4 */,
        '801162722' /* @5 */,
        '2014-03-06T13:30:03' /* @6 */,
        '801162722' /* @7 */,
        '2014-03-06T13:30:03' /* @8 */)

我在这里结束了。我已经尝试过以各种方式更改映射,但我所能做的就是让它抛出不同的异常。我没看到什么?

1 个答案:

答案 0 :(得分:0)

存在一对一的关系。两个实体的主键相同。

在从属表上,主键也是相关实体的外键。

在你的例子中:

public class ResponseSeries : TrackedEntity
{
    public ResponseSeries()
    {
        Responses = new Collection<Response>();
    }
    public Int32 ResponseSeriesId { get; set; }

    public virtual TabletUserSession TabletUserSession { get; set; }
    public virtual ICollection<Response> Responses { get; set; }

}

public class TabletUserSession : TrackedEntity
{
    // this should not exist
    public Int32 TabletUserSessionId { get; set; }

    // this should be the primary key of this entity
    // it is also the foreign key to the ResponseSeriesId
    public Int32 ResponseSeriesId { get; set; }
    public Int32? TabletId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime? ClosedDate { get; set; }

    public virtual Tablet Tablet { get; set; }
    public virtual ResponseSeries ResponseSeries { get; set; }
}

ResponseSeriesId是主键,是关系中的主要实体。在这种情况下,TabletUserSession实体的主键需要是ResponseSeriesId。它没有自己的身份,因为否则它不是真正的一个零或一个。