Code First conventions confusion

久未见 提交于 2019-12-25 04:05:44

问题


Models:

public class Status
{
    public int Id { get; set; }
}

public class Podcast
{
    public int Id { get; set; }

    public virtual Status Status { get; set; }
}

The Podcast table has the StatusId column, and this column is a foreign key. In this case I've got the following error message: Invalid column name 'Status_Id'. Why? - Many times I faced that articles with such examples. This is the first question. Ok, no problem - i've added an underscore character to these columns: Sttaus_Id and so on. Now it seems that everything works fine, but when I modify my model by the following way:

public class Podcast
{
    public int Id { get; set; }

    public int Status_Id { get; set; }

    public virtual Status Status { get; set; }
}

Now I get the following error: Invalid column name 'Status_Id1'. Why? I can't use the DropDownListFor helper without these xx_id properies.


回答1:


I believe the issue here is that you have created your DB first and created a column named StatusId for your FK reference but you haven't told EF that you are using a non-default column name for your FK.

the following will give you the structure you are after (ps i agree with your naming convention i personally dislike the _ in fk ids)

    public class MyContext : DbContext
    {
        public DbSet<Podcast> Podcasts { get; set; }
        public DbSet<Status> Status { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Podcast>().HasOptional(p => p.Status)
                .WithMany().HasForeignKey(p => p.StatusId);
            base.OnModelCreating(modelBuilder);
        }
    }

    public class Status
    {
        public int Id { get; set; }
    }

    public class Podcast
    {
        public int Id { get; set; }

        public int? StatusId { get; set; }
        public virtual Status Status { get; set; }
    }



回答2:


The convention at least for the foreign key field is table name + field name, so in your case StatusId without the underscore. But I'm not sure why it says invalid column name Status_Id1.

Remove the underscore, and try again. If you still get an error message, please make an edit to your question with the results.



来源:https://stackoverflow.com/questions/10614377/code-first-conventions-confusion

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