Entity Framework code first seems confused on my dbo table names after I tweaked the migration file

醉酒当歌 提交于 2019-12-11 12:56:47

问题


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.



来源:https://stackoverflow.com/questions/18895477/entity-framework-code-first-seems-confused-on-my-dbo-table-names-after-i-tweaked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!