model builder add one column more?

277 views Asked by At

I use EF code first.

It's my modelbuilder

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Market>()
            .HasRequired(s => s.State)
            .WithMany()
            .HasForeignKey(s => s.StateId)
            .WillCascadeOnDelete(false);
    }

and State Class :

public class State
{
    public State()
    {
        Markets = new HashSet<Market>();
    }

    [Key]
    public int StateId { get; set; }

    public string StateName { get; set; }

    // navigation property

    public virtual ICollection<Market> Markets  { get; set; }
}

and Market class :

public class Market
{
    [Key]
    public int MarketId { get; set; }

    public string MarketName { get; set; }

    public int StateId { get; set; }

    // navigation property

    public virtual State State { get; set; }

}

Of course I remove extra code.

Problem is when I use this code , an State_StateId column add to my Market table in database, and when I do not use modelbuilder an error occurred with message loop code and ... (I say that I remove extra code), so how can I use code first without this "State_StateId" extra column.

excuse me for bad english writing.

1

There are 1 answers

1
CodeNotFound On BEST ANSWER

If you want to remove State_StateId column set the configuration completely like the code below and don't let WithMany empty:

modelBuilder.Entity<Market>()
        .HasRequired(s => s.State)
        .WithMany(p => p.Markets)
        .HasForeignKey(s => s.StateId)
        .WillCascadeOnDelete(false);

Or you can just remove the Fluent API configuration and let EF use the default configuration convention and will set all tables, primary keys, foreign keys and column name for you.