外键问题和EF插入记录

时间:2014-07-30 20:21:55

标签: c# entity-framework

我有以下课程:

public class Instrument
{
    public int Id { get; set; }
    public string Book { get; set; }
    public string Page { get; set; }
}
public class Order
{
    public int Id { get; set; }
    public string OrderName { get; set; }
    public ICollection<MatchedInstrument> MatchedInstruments { get; set; }
}
public class MatchedInstrument
{
    public int Id { get; set; }
    //public int InstrumentId { get; set; }
    public Instrument Instrument { get; set; }
    public bool IsIncluded { get; set; }
    public string Notes { get; set; }
}

以下EF DbContext:

    public class AppContext : DbContext
{
    public DbSet<Instrument> Instruments { get; set; }
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>().HasKey(o => o.Id)
           .HasMany(o => o.MatchedInstruments)
           .WithMany().Map(m => 
           {
              m.MapLeftKey("orderid");
              m.MapRightKey("selectedmatchid");
              m.ToTable("ordermatchedinstruments");
           });

        modelBuilder.Entity<MatchedInstrument>().HasKey(m => m.Id)
           .HasRequired(m => m.Instrument)
           .WithRequiredPrincipal();
   }
}

请注意, OrderMatchedInstruments 表是一个连接表,它只包含两列:orderid和matchedinstrumentid(与 MatchedInstruments 表相关)。 MatchedInstruments 表的架构如下所示:

[dbo].[MatchedInstruments](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [IsIncluded] [bit] NOT NULL,
    [Notes] [varchar](max) NULL,
    [InstrumentId] [int] NOT NULL

这一切似乎都适用于查询数据。我可以查询订单并包含其匹配的工具。

然而,当我尝试向订单添加新的MatchedInstrument时,我收到一条错误,告诉我在MatchedInstrument表中不能将InstrumentId设为null。

...
// Demo Code - count on non-null objects
var instrument = _context.Instruments.FirstOrDefault(); 
var order = _context.Orders.SingleOrDefault(o => o.Id == 5);
order.MatchedInstruments.Add(new MatchedInstrument() { Instrument = instrument });
_context.SaveChanges();    

这使我认为我需要将一个InstrumentId属性添加到MatchedInstrument类。但是,我认为只要符合相应的命名约定,EF就可以在没有外键的情况下正常工作。 IOW,我有Instrument的导航属性这一事实会让我认为它会自动查看InstrumentId的表格,因此会为我填充。

情况并非如此,或者我是否遗漏了EF如何处理外键的问题?

3 个答案:

答案 0 :(得分:0)

将以下属性添加到模型中的每个ID属性:

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

答案 1 :(得分:0)

我刚开始工作了。我在绘图中错误地设置了我的关系。我从使用WithRequiredPrincipal更改为以下内容:

    modelBuilder.Entity<MatchedInstrument>().HasKey(m => m.Id)
       .HasRequired(m => m.Instrument)
       .WithMany().HasForeignKey(m => m.InstrumentId);

不确定为什么我认为我需要使用WithRequiredPrincipal(),但这肯定解决了我的问题。

答案 2 :(得分:-1)

我发现你没有发送InstrumentId,而是发送对象Instrument,这就是你问题的原因,因为你的架构有InstrumentId作为非空整数而你发送的是整个Instrument Object,你只需要确保您真正需要哪些数据,然后更改代码。

...素不相识了Ing。 JorgePérezBárcenas

相关问题