实体框架中的不需要的外键约束6.1代码优先

时间:2015-07-11 16:08:09

标签: c# sql-server entity-framework

我的EF项目在我的模型中有一个Day类,一个WeekEnd类和一个Week类。我使用[InverseProperty][Required]属性标记了类:

public class Day
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DayId { get; set; }

    public DateTime UtcDayStart { get; set; }

    public string DayName { get; set; }

    public int ISOWeekNumber {get; set; }

    [InverseProperty("Days")]
    public virtual Week Week { get; set; }

    [InverseProperty("Days")]
    public virtual WeekEnd WeekEnd { get; set; }
}

public class WeekEnd
{
    Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int WeekEndId { get; set; }

    public DateTime UtcWeekEndStart { get; set; }

    public int ISOWeekNumber { get; set; }

    [Required]
    [InverseProperty("WeekEnd")]
    public virtual Week Week { get; set; }

    [InverseProperty("WeekEnd")]
    public virtual ICollection<Day> Days { get; set; }
}

public class Week
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int WeekId { get; set; }

    public DateTime UtcWeekStart { get; set; }

    public int ISOWeekNumber { get; set; }

    [InverseProperty("Week")]
    public virtual WeekEnd WeekEnd { get; set; }

    [InverseProperty("Week")]
    public virtual ICollection<Day> Days { get; set; }
}

问题是SQL Server不允许我为Day Null插入WeekEnd_WeekEndId表格数据。因为并非所有星期都属于周末,这对我来说是一个问题。

插入声明:

INSERT INTO [database].[dbo].[Days] (DayId, UtcDayStart, ISOWeekNumber,
DayName, WeekEnd_WeekEndId, Week_WeekId)
VALUES ('3', '1/3/2005 12:00 AM', '1', 'Monday', '', '1')

SQL Server错误消息是:

  

Msg 547,Level 16,State 0,Line 1
  INSERT语句与FOREIGN KEY约束冲突&#34; FK_dbo.Days_dbo.WeekEnds_WeekEnd_WeekEndId&#34;。冲突发生在数据库&#34;数据库&#34;,table&#34; dbo.WeekEnds&#34;,column&#39; WeekEndId&#39;。

如何设置属性或可能添加外键列(或列)以使代码优先迁移不在DaysWeekEnds之间创建外键约束?

编辑:

所以在完成这个并尝试不同的FluentAPI语句和属性后,我认为模型很好。它是不会起作用的SQL Server INSERT语句。如果我这样做:

INSERT INTO [database].[dbo].[Days] (DayId, UtcDayStart, ISOWeekNumber,
DayName, Week_WeekId)
VALUES ('3', '1/3/2005 12:00 AM', '1', 'Monday', '1')

然后在实际属于UPDATE的那些日子里执行以下WeekEnd

UPDATE [database].[dbo].[Days] SET WeekEnd_WeekEndId = 'X'  WHERE DayId ='Y'

然后我的表在周一到周五的日期NullWeekEnd_WeekEndId个{(1}}值(就像我想要的那样)。

我不确定这是否有资格作为答案,因为我对此不熟悉。所以我会让其他人提出答案。

1 个答案:

答案 0 :(得分:0)

要将关系配置为0..many而不是1..many,您需要调整模型。最简单的方法是使用FluentAPI。

protected override void OnModelCreating(DbModelBuilder modelBuilder) {

    modelBuilder.Entity<Week>()
                .HasMany<Day>(w => w.Days)
                .WithOptional(d => d.Week);

    modelBuilder.Entity<WeekEnd>()
                .HasMany<Day>(we => we.Days)
                .WithOptional(d => d.WeekEnd);
}