Bercovici Adrian
Bercovici Adrian

Reputation: 9360

Can not set up one to many relationship with EF fluent API

I am trying to configure a one to many relationship using EF Core via fluent api and i keep getting the following error :

The expression 'x => x.parent' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'. (Parameter 'propertyAccessExpression')'

Model(s)

        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; }
        }

Context

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) { }
        }

Usage

 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();
}

Upvotes: 0

Views: 122

Answers (1)

ilkerkaran
ilkerkaran

Reputation: 4344

parent in Child class is a field. It should be public property. Please see for more information https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/fluent/types-and-properties#property-mapping

Upvotes: 2

Related Questions