Entity Framework code first seems confused on my d

2019-08-11 03:44发布

问题:

I've just begun using Entity Framework 5 (Code First Migrations). I think my issue may just be a given to someone that's worked with this a bit longer than I have (this is our first project giving it a go).

I have 3 tables involved. One is a cross reference table. The gist of the classes is as follows:

public class Person
{
      //person properties
      public virtual List<Roles> Roles {get;set;}
}

public class Role
{
      //Role properties
      public virtual List<Person> Persons {get;set;}
}

Adding a migration here lead to a file where EntityFramework proposed a table name of:

    CreateTable(
        "dbo.PersonRoles"...

I changed this to:

    CreateTable(
        "dbo.PersonRolesXRef"...

That worked. The database updated and all that good stuff; however, when I do:

foreach(var role in Person.Roles() )
{
...
}

I get an inner exception that reads:

"Invalid object name 'dbo.PersonRoles' ..."

It seems like EF is unaware that I changed the name of the table even though that's in the migration file. Do I need to add an annotation somewhere?

回答1:

You're running into the naming convention that Code First is setup to expect. Except in rare occasions, you should never modify the automatically generated mirgration files.

If you want to change the table name of your cross reference table, you'll need to create a third entity:

[Table("PersonRolesXRef")]
public class PersonRoles {
    public virtual Person Person { get; set; }
    public virtual Role Role { get; set; }
}

This will let you control the many-to-many table that Entity Framework creates. Then use the TableAttribute to set what you want the table name to be in SQL.