Reputation: 21
I have a model in which 3 classes (part of the complete model)
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public string District { get; set; }
}
public class Customer
{
public string? Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public City? City { get; set; }
}
public class Order
{
public int Id { get; set; }//OrderId
public Customer? Customer { get; set; }
//more properties in Customer structure
}
And the following tables:
tbl_customers
---------------------------------------------------------------------
id | customer_id | customer_first_name | customer_last_name | city_id
tbl_city
-----------------------------------------------------------
city| city_desc| dist
All the data from Order
and Customer
should be poured into table tbl_customers
.
In Customer
there is City
property which mapped to foreign key
to tbl_city
So, I build a Context
(Instruction)
public class EntityContext: DbContext
{
public DbSet<Order> Orders { get; set; }
public DbSet<Customer> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer("myConnectionString");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<City>(c =>
{
c.ToTable("tbl_city")
.HasKey(c => c.Id);
c.Property(c => c.Id)
.HasColumnName("city");
c.Property(c => c.Name)
.HasColumnName("city_desc");
c.Property(c => c.District)
.HasColumnName("dist");
});
modelBuilder.Entity<Order>(c =>
{
c.ToTable("tbl_customers")
.HasKey(c=>c.Id);
c.Property(c=>c.Id).HasColumnName("id");
c.HasOne(e => e.Customer)
.WithOne()
.HasForeignKey("customer_id");
});
modelBuilder.Entity<Customer>(c =>
{
c.ToTable("tbl_customers");
c.Property(c => c.Id)
.HasColumnName("customer_id");
c.Property(c => c.FirstName)
.HasColumnName("customer_first_name");
c.Property(c => c.LastName)
.HasColumnName("customer_last_name");
});
}
}
But I get an error:
System.InvalidOperationException: Cannot use table 'tbl_customers' for entity type 'Order' since it is being used for entity type 'Customer' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'Order' on the primary key properties and pointing to the primary key on another entity type mapped to 'tbl_customers'.
at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IReadOnlyList
1 mappedTypes, StoreObjectIdentifier& storeObject, IDiagnosticsLogger
1 logger)
at Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerModelValidator.ValidateSharedTableCompatibility(IReadOnlyList1 mappedTypes, StoreObjectIdentifier& storeObject, IDiagnosticsLogger
1 logger)
There is similar question without solution to the problem with different context
Upvotes: 0
Views: 305