[英]EF Core 3: Configure backing field of navigation property
考慮下面的類。 它試圖保護對_assignedTrays的訪問。
實際上,它工作得很好,因為 EF 自動將支持字段_assignedTrays
鏈接到屬性AssignedTrays
- 按照約定(msdn )
public class Rack
{
private List<Tray> _assignedTrays = new List<Tray>();
private Rack()
{
}
public Rack(string rackId)
{
this.Id = rackId;
}
public string Id { get; private set; }
public IReadOnlyList<Tray> AssignedTrays => this._assignedTrays.AsReadOnly();
public void Assign(params Tray[] trays)
{
this._assignedTrays.AddRange(trays);
}
}
問題是,我們的編碼風格禁止在變量名中使用下划線 ;-)
根據其他代碼示例( 此處),應該可以將_assignedTrays
重命名為assignedTrays
並明確通知EF OnModelCreating
中的OnModelCreating
:
modelBuilder.Entity<Rack>(e =>
{
e.Property(t => t.AssignedTrays).HasField("assignedTrays");
});
但這給了我以下例外:
System.InvalidOperationException: The property 'Rack.AssignedTrays' is of type 'IReadOnlyList<Tray>' which
is not supported by current database provider. Either change the property CLR type or ignore the property
using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
我在這里缺少什么? 它不應該工作嗎?
文檔不反映實際的規則,因為<camel-cased property name>
(以下簡稱“標准” C#支持字段命名約定)肯定是支持的,甚至可能具有最高優先級。
但是假設您的命名約定不受支持。 您仍然可以映射支持字段,但不能使用Property
fluent API 來實現,因為根據 EF Core 術語,導航屬性不是“屬性”,而是“導航”。 這適用於所有 fluent、更改跟蹤等 API。
為了配置導航,您需要訪問關系構建器。 然后,您可以使用關聯元數據的PrincipalToDependent
和DependentToPrrncipal
屬性來訪問/配置關系的兩端。
或者直接使用元數據 API(目前還沒有專門的 fluent API)。
例如:
modelBuilder.Entity<Rack>()
.FindNavigation(nameof(Rack.AssignedTrays))
.SetField("assignedTrays");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.