簡體   English   中英

外鍵出現問題並使用EF插入記錄

[英]Trouble with foreign key and inserting record with EF

我有以下課程:

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

這一切似乎都可以很好地用於查詢數據。 我能夠查詢訂單並包括其匹配的工具。

但是, 當我嘗試向訂單中添加新的MatchInstrument時,出現一條錯誤消息,告訴我InstrumentId在MatchInstrument表中不能為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();    

這使我認為我需要向MatchedInstrument類添加InstrumentId屬性。 但是,我認為只要遵循適當的命名約定,EF就可以在沒有外鍵的情況下正常工作。 IOW,我具有Instrument的導航屬性這一事實使我認為它會自動在表中查找InstrumentId,因此會為我填充它。

是不是這樣,或者我在EF如何處理外鍵方面缺少某些東西?

將以下屬性添加到模型中的每個ID屬性:

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

我剛剛得到這個工作。 我在映射中建立的關系不正確。 我從使用WithRequiredPrincipal更改為以下內容:

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

不知道為什么我認為我需要使用WithRequiredPrincipal(),但這肯定解決了我的問題。

如我所見,您發送的不是InstrumentId,而是對象Instrument,這是造成問題的原因,因為您的架構將InstrumentId作為Not Null整數,並且您發送的是整個Instrument對象,因此您只需要確保您真正需要什么數據,然后更改代碼。

Grettings ... Ing。 豪爾赫·佩雷斯·巴爾恰納斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM