EF Core modelbuilder not a valid expression fluent api

c# ef-fluent-api entity-framework-core

Question

When i try to do the command add-migration in my package manager I get the following error.

The expression 'a => a.Customer' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'.

This is an image of the class diagram classDiagram

and the code of my BankContext.cs class where I am defining the relationships between the tables

namespace Bank.Datalayer
{
    public class BankContext : DbContext
    {
        public DbSet<Account> Accounts { get; set; }
        public DbSet<City> Cities { get; set; }
        public DbSet<Customer> Customers { get; set; }
        // TODO: Vul deze klasse aan
        public BankContext() { }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server = (localdb)\\mssqllocaldb; Database =  BankDB; Trusted_Connection = true");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Primary key
        modelBuilder.Entity<City>()
            .HasKey(c => c.ZipCode);
        modelBuilder.Entity<Account>()
            .HasKey(a => a.Id);
        modelBuilder.Entity<Customer>()
            .HasKey(c => c.CustomerId);

        //Foreign Keys
        modelBuilder.Entity<Account>()
            .HasOne(a => a.Customer)
            .WithMany(c => c.Accounts)
            .HasForeignKey(c => c.CustomerId);


        modelBuilder.Entity<City>()
            .HasMany(c => c.Customers)
            .WithOne(customer => customer.City)
            .HasForeignKey(c => c.Name);

        base.OnModelCreating(modelBuilder);
    }

    public void CreateOrUpdateDatabase()
    {
        Database.Migrate();
    }
}

Last but not least the code of my Account class where all the trouble is happening

namespace Bank.DomainClasses
{
    public class Account
    {
        // TODO: vul deze klasse aan
        public int Id { get; set; }
        public int AccountNumber { get; set; }
        public decimal Balance { get; set; }
        public AccountType AccountType { get; set; }
        public int CustomerId { get; set; }

        public Customer Customer;
    }
}

I already tried making the customer property "virtual" but it wouldn't work.

1
0
1/24/2019 1:12:25 AM

Accepted Answer

You need to change public Customer Customer; to public Customer Customer { get; set; }. Currently Customer is a field not a property.

1
1/23/2019 1:30:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow