Deshan Medaduwa
Deshan Medaduwa

Reputation: 23

How to map new class to an existing table using c# Fluent API?

In my application, there is a many-to-many relationship between two entities (ChartOfAccount & GL). Once I create the relationship a new table got created (ChartOfAccountGLs). Now I tried to create a new class to map those two entities with one-to-many relationship (ChartOfAccountGL-->ChartOfAccount & ChartOfAccounGL-->GL). But when I tried to update, database package manager console gave this error

"There is already an object named 'FK_dbo.ChartOfAccountGLs_dbo.ChartOfAccounts_ChartOfAccountId' in the database. Could not create constraint or index. See previous errors."

Below shows my ChartOfAccountGL class:

[Table("ChartOfAccountGLs")]
public class ChartOfAccountGL
{
    public int ChartOfAccountId { get; set; }
    public int GLId { get; set; }

    public ChartOfAccount ChartOfAccount { get; set; }
    public GL GL { get; set; }
}

ChartOfAccountGLConfiguration :

public class ChartOfAccountGLConfiguration : EntityTypeConfiguration<ChartOfAccountGL>
{
    public ChartOfAccountGLConfiguration()
    {
        //Define two composite keys
        HasKey(k => new { k.ChartOfAccountId, k.GLId });

        Property(a => a.ChartOfAccountId)
            .HasColumnName("ChartOfAccountId");

        Property(b => b.GLId)
            .HasColumnName("GLId");

        //Mapping classes
        HasRequired(a => a.ChartOfAccount)
            .WithMany(b => b.ChartOfAccountGL);

        HasRequired(f => f.GL)
            .WithMany(b => b.ChartOfAccountGL);
    }
}

Does anyone has an idea where have I done the mistake??

Upvotes: 1

Views: 187

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

It's a known problem for when you upgrade the model. In EF6 you can use ignore changes but in ef core, check this: https://github.com/dotnet/efcore/issues/4237

There is no equivalent for IgnoreChanges when generating migrations right now. Not on powershell, or using ef migrations add. This needs to come to EF7 and is a fundamental part of the migration work, specially for apps that are working with existing tables.

If you are using ef core, try this (from a comment in the issue):

This is probably just stating the obvious... but as a workaround for the moment you can generate a migration and then delete the code from the Up/Down methods.

Upvotes: 1

Related Questions