代码第一约定混乱 [英] Code First conventions confusion
问题描述
模型:
public class Status
{
public int Id { get; set; }
}
public class Podcast
{
public int Id { get; set; }
public virtual Status Status { get; set; }
}
Podcast表具有StatusId列,此列是外键。在这种情况下,我收到以下错误消息:无效的列名称为'Status_Id'。
为什么? - 很多时候我面对这样的例子的文章。这是第一个问题。
好的,没问题 - 我已经添加了一个下划线字符到这些列:Sttaus_Id等等。
现在看来,一切都正常,但是当我通过以下方式修改我的模型时:
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; }
}
现在我收到以下错误:列无效名称'Status_Id1'。
为什么?我不能使用没有这些xx_id属性的DropDownListFor帮助器。
Now I get the following error: Invalid column name 'Status_Id1'.
Why? I can't use the DropDownListFor helper without these xx_id properies.
推荐答案
我相信这里的问题是你创建了你的数据库先创建一个名为StatusId的FK参考列,但是您没有告诉EF您正在为FK使用非默认列名。
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.
以下将给您您的结构(ps我同意您的命名约定,我个人不喜欢_在fk ids)
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; }
}
这篇关于代码第一约定混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!