【问题标题】:Why I am I getting "'Bars' cannot be used as a property on entity type 'Foo'" in my setup?为什么我在设置中收到“'Bars' 不能用作实体类型 'Foo' 的属性”?
【发布时间】:2021-01-16 17:28:27
【问题描述】:

从概念上讲,我想要实现的相当于

public interface IFoo
{
    IReadOnlyCollection<Bar> Bars { get; }
    void AddBar(string barName);
}

即你创建了Bars“虽然”Foo

我有一个相当于

的设置
public class Foo
{
     public int Id { get; protected set; }

     public IReadOnlyCollection<Bar> Bars => this._bars;
  
     protected readonly List<Bar> _bars;

     protected Foo(Guid id, List<Bar> bars)
     {
         this.Id = id;
         this._bars = bars;
     }

     // default ctor for ORM
     protected Foo() { }

     public static Foo Create(Guid id, params string[] barNames)
     {
          var foo = new Foo(id, new List<Bar>());
          foreach (var barName in barNames)
          {
              foo.AddBar(barName);
          }
          return foo;
     }

     public void AddBar(string name)
     {
         if (string.IsNullOrWhitespace(name))
         {
             throw new ArgumentException("Bar name cannot be emptiness.");
         }

         if (this._bars.Any(b => b.Name == name))
         {
             throw new InvalidOperationException($"Cannot add bar '{name}' as it already is added.");
         }

         this._bars.Add(new Bar(Guid.NewGuid(), this, this.Id, name));
     }
}

public class Bar
{
     public Guid Id { get; protected set; }

     public Foo Foo { get; protected set; }
  
     public Guid FooId { get; protected set; }

     public string Name { get; protected set ; }

     internal Bar(Guid id, Foo foo, Guid fooId, string name)
     {
         this.Id = id;
         this.Foo = foo;
         this.FooId = fooId; 
         this.Name = name;
     }
 
     // default ctor for ORM
     protected Bar() { }
}

到 SQL 的映射等价于

modelBuilder.Entity<Foo>().ToTable("Foos");
modelBuilder.Entity<Foo>().HasKey(f => f.Id);
modelBuilder.Entity<Foo>().HasMany(f => f.Bars).WithOne(b => b.Foo).HasForeignKey(b => b.FooId);
modelBuilder.Entity<Foo>().Property(f => f.Bars).HasField("_bars");

modelBuilder.Entity<Bar>().ToTable("Bars");
modelBuilder.Entity<Bar>().HasKey(b => b.Id);
modelBuilder.Entity<Bar>().Property(b => b.Name).IsRequired();
modelBuilder.Entity<Bar>().HasOne(b => b.Foo).WithMany(f => f.Bars).HasForeignKey(b => b.FooId);

当我Add-Migration 我得到错误

'Bars' 不能用作实体类型 'Foo' 的属性,因为它是 配置为导航

【问题讨论】:

    标签: c# entity-framework orm entity-framework-core


    【解决方案1】:

    这个

    modelBuilder.Entity<Foo>().Property(f => f.Bars).HasField("_bars");
    

    没有必要,因为 EF 永远不会分配集合导航属性,因此它不需要知道该属性有 Backing Field

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      相关资源
      最近更新 更多