2017-10-19 128 views
0

我試圖刪除我的實體與它相關的實體,但實體框架不想這樣做。EF核心不刪除相關實體

下面是代碼:

 var tr = _context.Trees 
      .Include(x => x.Translation) 
      .FirstOrDefault(x => x.Id == 2); 

     _context.Remove(tr); 
     _context.SaveChanges(); 

語境:

modelBuilder.Entity<Tree>().ToTable("h_tree"); 
    modelBuilder.Entity<Tree>().HasOne(x => x.Translation); 

樹類:

public class Tree 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual Translation Translation { get; set; } 
} 

任何人有任何想法,爲什麼相關的實體不能被刪除?

翻譯類:

public class Translation 
{ 
    public long Id { get; set; } 
    public string Pl { get; set; } 
    public string En { get; set; } 
    public string De { get; set; } 
    public string Cz { get; set; } 
    public string It { get; set; } 
    public string Ru { get; set; } 
    public string Fr { get; set; } 

    public Translation() 
    { 

    } 
} 
+0

在數據集中是否真的有id = 2的記錄? –

+0

當然可以。這是EF日誌: SET NOCOUNT ON; DELETE FROM [cat]。[h_tree] WHERE [id] = @ p0; SELECT @@ ROWCOUNT; – bielu000

回答

1

你似乎已經錯過了說這是否是一個對一個或一個一對多的關係。

.HasOne()需要與.With*()方法配對。 .WithOne().WithMany()


看來你的翻譯類缺少一個外鍵。

添加名爲TreeId的房產並在.WithOne()調用中使用該房產。

+0

我試過這個語法:modelBuilder.Entity ().HasOne(x => x.Translation).WithOne()。OnDelete(DeleteBehavior.Cascade); 但它不起作用。 – bielu000

+0

我有以下錯誤:無法確定在'Tree.Translation'和'Translation'之間檢測到的一對一關係的子/從屬方。要確定關係的子/從屬端,請配置外鍵屬性。 – bielu000

+0

@ bielu000那麼在'Translation'中你的外鍵字段是什麼?你爲什麼不把它放在你的.WithOne方法中? – nvoigt