Skip to content Skip to sidebar Skip to footer

Code First Conventions Confusion

Models: public class Status { public int Id { get; set; } } public class Podcast { public int Id { get; set; } public virtual Status Status { get; set; } } The Podca

Solution 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)

publicclassMyContext : DbContext
    {
        publicDbSet<Podcast> Podcasts { get; set; }
        publicDbSet<Status> Status { get; set; }

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

    publicclassStatus
    {
        publicint Id { get; set; }
    }

    publicclassPodcast
    {
        publicint Id { get; set; }

        publicint? StatusId { get; set; }
        publicvirtual Status Status { get; set; }
    }

Solution 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.

Post a Comment for "Code First Conventions Confusion"