Entity Framework appends "1" to table name and query fails

We have an e-commerce site that uses Web Api and Entity Framework. I recently created an ApiController for an object called "BundleProduct". When I call the GET method on the controller, I get System.Data.SqlClient.SqlException: Invalid object name 'dbo.BundleProducts1'.

Using the VS debugger, this is the query that runs (there are only two columns in this table, together form the primary key):

SELECT 
[Extent1].[Fk_BundleID] AS [Fk_BundleID], 
[Extent1].[Fk_ProductID] AS [Fk_ProductID]
FROM [dbo].[BundleProducts1] AS [Extent1]

      

There is no "BundleProducts1" table, it should be called "BundleProducts". I've searched the code and can't find any instances that use the name "BundleProducts1".

The BundleProducts table represents a many-to-many relationship between the Bundles table and the Products table. This particular table only has two columns and both together are the primary key. I looked at the DbContext class and its only references for BundleProducts are:

public DbSet<BundleProduct> BundleProducts { get; set; }

modelBuilder.Entity<Bundle>()
.HasMany(e => e.Products)
.WithMany(e => e.Bundles)
.Map(m => m.ToTable("BundleProducts")
.MapLeftKey("Fk_BundleID")
.MapRightKey("Fk_ProductID"));

      

Why does EF add "1" to the table name, and what can I do to change this?

+3


source to share


1 answer


When you use many-to-many mapping ( HasMany - WithMany

), EF will use the name- hidden association class BundleProducts

.

The problem is that you also added the visible class BundleProducts

. EF is trying to accomplish what you were instructed to do: map both classes to a table and then run into a name conflict. The visible class is victimized and renamed.



You either need to remove the visible class of your model, or convert display "many-to-many" in the two display a "one-to-many" with BundleProducts

the middle: Bundle 1 - n BundleProduct n - Product

.

+5


source







All Articles