无法与EF Fluent API建立一对多关系

时间:2019-12-13 13:46:39

标签: entity-framework ef-fluent-api .net-core-3.1

我正在尝试通过fluent api使用 public class Parent { public int ID { get; set; } public string Name { get; set; } public ICollection<Child> Children { get; set; } } public class Child { public int ID { get; set; } public string Name { get; set; } public Parent parent; public int ParentId { get; set; } } 配置一对多关系,但不断出现以下错误:

  

表达式'x => x.parent'不是有效的属性表达式。的   表达式应该表示一个简单的属性访问:'t =>   t.MyProperty”。 (参数“ propertyAccessExpression”)”

型号

public class MyContext : DbContext {
            public DbSet<Parent> Parents { get; set; }
            public DbSet<Child> Children { get; set; }
            protected override void OnModelCreating(ModelBuilder modelBuilder) {

                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<Child>().HasKey(x => x.ID);
                modelBuilder.Entity<Parent>().HasKey(x => x.ID);

                modelBuilder.Entity<Child>()
                                .HasOne(x => x.parent)
                                .WithMany(y => y.Children)
                                .HasForeignKey(t => t.ParentId);
            }

            public MyContext(DbContextOptions options):base(options) { }
        }

上下文

 static async Task Main(string[] args)
        {
            string connectionString = "[someconnectionstring]"
            var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
            optionsBuilder.UseSqlServer(connectionString);
            MyContext context = new MyContext(optionsBuilder.Options);
            await context.Parents.AddAsync(new Parent { 
                                               Name = "myparent", 
                                               Children = new List<Child>() {
                                                                new Child { Name = "Child1" },
                                                                new Child { Name = "Child2" } }
                                               }); //i am getting the error here
            await context.SaveChangesAsync();
}

用法

from selenium import webdriver
chrom_path = r"C:\Users\user\sof\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrom_path)
link = 'https://www.google.com/'
driver.get(link)
s = driver.page_source
print((s.encode("utf-8")))
driver.quit()

1 个答案:

答案 0 :(得分:1)

parent类中的

Child是一个字段。它应该是公开的财产。有关更多信息,请参见https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/fluent/types-and-properties#property-mapping