[英]How to configure Owned type referencing another entity in ef core 6
我有以下名為 Slot 的實體。
public class Slot : Entity
{
public virtual SnackPile SnackPile { get; set; }
}
這里的 SnackPile 是一個 ValueObject,沒有自己的表。 它歸插槽所有。 SnackPile 看起來像這樣。
public sealed class SnackPile : ValueObject<SnackPile>
{
public static readonly SnackPile Empty = new SnackPile(Snack.None, 0, 0m);
public Snack Snack { get; } // Please note this Snack, we will come to this.
public int Quantity { get; }
public decimal Price { get; }
private SnackPile() { }
}
所以要配置它,我有以下內容。
modelBuilder.Entity<Slot>().OwnsOne(slot => slot.SnackPile, slotToSnackpile =>
{
slotToSnackpile.Property(ss => ss.Price).IsRequired();
slotToSnackpile.Property(ss => ss.Quantity).IsRequired();
//slotToSnackpile.Navigation(p => p.Snack).IsRequired(); // This is not working.
}).Navigation(slot => slot.SnackPile).IsRequired();
到目前為止,一切都很好。
現在 SnackPile 具有屬性 Snack,這是一個實體。 如何配置這個? 如您所見,我嘗試添加此
slotToSnackpile.Navigation(p => p.Snack).IsRequired(); // This is not working.
它給出了以下錯誤。
Navigation 'SnackPile.Snack' was not found. Please add the navigation to the entity type before configuring it.
也嘗試了以下兩個,但無濟於事。
//slotToSnackpile.Property(ss => ss.Snack).IsRequired();
這給出了以下錯誤。 The property 'SnackPile.Snack' is of type 'Snack' which is not supported by the current database provider. Either change the property CLR type, or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
有了這個
//slotToSnackpile.Property(ss => ss.Snack.Id).IsRequired();
我得到了錯誤。 The expression 'ss => ss.Snack.Id' is not a valid member access expression. The expression should represent a simple property or field access: 't => t.MyProperty'. (Parameter 'memberAccessExpression')
卡住了:(有什么想法嗎?
默認情況下,EF Core 僅映射具有公共 getter和任何 setter (可能是私有的、受保護的等)的屬性(原始或類似導航)。 由於您的所有屬性(包括有問題的屬性)都只能獲取(沒有設置器),因此您必須明確地對它們進行 map。
對於原始屬性,您使用Property
fluent API。 但是對於導航屬性,您需要關系流暢的 API,例如Has
/ With
對。 在你的情況下:
slotToSnackpile.HasOne(e => e.Snack).WithMany().IsRequired();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.