升级到RC后,创建多对多关系的实体失败

时间:2011-04-04 20:57:01

标签: c# entity-framework entity-framework-4.1 ef-code-first poco

我有一个包含3个简单表,几个POCO类和一个用代码创建的DBContext的项目,没有edml文件。以下代码设置用于处理实体框架代码的测试 - 首先,我编辑了DbContext代码,因为模型构建器从测试版改为RC

表(简单表多对多表的字段声明为带有级联删除的外键):

CREATE TABLE [dbo].[Bookings](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NOT NULL,
    [AccountId] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Bookings] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)

CREATE TABLE [dbo].[Units](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [Description] [nvarchar](1000) NULL,
    [Beds] [int] NOT NULL,
 CONSTRAINT [PK_Units] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)

CREATE TABLE [dbo].[UnitBookings](
    [UnitId] [int] NOT NULL,
    [BookingId] [int] NOT NULL
) ON [PRIMARY]

POCOS:

public class Unit
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string Name { get; set; }
    public string Description { get; set; }
    [Required]
    public int Beds { get; set; }
    public ICollection<Booking> Bookings { get; set; }
}

public class Booking
{
    [Key]
    public int ID { get; set; }
    [Required]
    public DateTime StartDate { get; set; }
    [Required]
    public DateTime EndDate { get; set; }
    [Required]
    public string AccountId { get; set; }
    public ICollection<Unit> Units { get; set; }
}

数据库上下文

public class BookingDb : DbContext
{
    public DbSet<Booking> Bookings { get; set; }
    public DbSet<Unit> Units { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Unit>()
            .HasMany(u => u.Bookings)
            .WithMany(b => b.Units)
            .Map(m => m.MapLeftKey("BookingId").MapRightKey("UnitId").ToTable("UnitBookings"));
    }
}

创建预订(bookingCarrrier是由前端层提供的帮助类)

public static bool CreateBooking(BookingCarrier carrier, out string statusMsg)
{
    using (var db = new BookingDB())
    {
        var validator = new BookingValidator(2, 3);
        Booking booking = CreateBooking(carrier, db);
        if (validator.Validate(booking.AccountId, booking, -1, out statusMsg)
        {
            db.Bookings.Add(booking);
            db.SaveChanges();
            return true;
        }
        return false;
    }
}

private static CreateBooking(BookingCarrier carrier, BookingDB db)
{
    var units = new List<Unit>();
    if (carrier.SelectedUnit == 0)
        units.AddRange(db.Units.ToList());
    else
        units.Add(db.Units.Find(carrier.SelectedUnit));
    return new Booking
        {
            AccountId = carrier.AccountId,
            EndDate = carrier.EndDate,
            StartDate = carrier.StartDate,
            Units = units
        };
}

执行此代码时,EF会抛出SqlException并显示以下消息:

  

INSERT语句与之冲突   FOREIGN KEY约束   “FK_UnitBookings_Units”。冲突   发生在数据库“grashult.dk”中,   表“dbo.Units”,列'ID'。

测试版中并非如此。

我知道这是一个相当简单的设置,但由于这是一个爱好项目,我正在尝试看看这样的事情是多么简单。

是否有人知道导致此行为的更改? EF 4.1仍然可以实现这样的功能,还是我必须甩掉数据模型设计师?

此致 Jesper Hauge

1 个答案:

答案 0 :(得分:7)

您必须交换密钥映射:

modelBuilder.Entity<Unit>()
            .HasMany(u => u.Bookings)
            .WithMany(b => b.Units)
            .Map(m => m.MapLeftKey("UnitId")
                       .MapRightKey("BookingId")
                       .ToTable("UnitBookings"));

我刚刚对其进行了测试,问题是Booking.Id存储在UnitIdUnitId Booking.Id中。