我與EF代碼第一次嘗試,並創建實體Article
: 在子類EF代碼第一次實體列
public class Article
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ArticleId { get; set; }
[Required, MaxLength(50)]
public string Title { get; set; }
public DateTimeRange Published { get; set; }
}
因爲會有許多實體需要一個範圍,我認爲這將是更容易地創建一類DateTimeRange
:
public class DateTimeRange
{
[Required]
public DateTime From { get; set; }
public DateTime? To { get; set; }
}
代碼生成工作得很好,這是結果:
CreateTable(
"dbo.Articles",
c => new
{
ArticleId = c.Guid(nullable: false, identity: true),
Title = c.String(nullable: false, maxLength: 50),
Published_From = c.DateTime(nullable: false),
Published_To = c.DateTime(),
})
.PrimaryKey(t => t.ArticleId);
但是,我想要生成沒有下劃線的列名。我試着給列From
和To
特定名稱:
[Required, Column("PublishedFrom")]
public DateTime From { get; set; }
[Column("PublishedTo")]
public DateTime? To { get; set; }
這完美的作品:
PublishedFrom = c.DateTime(nullable: false),
PublishedTo = c.DateTime()
事情是:就像我說的,我想在幾個實體,也許用這個甚至在同一實體中多次出現,因此在DateTimeRange
中給出一個固定名稱將不起作用。我寧願只是說能連接沒有下劃線的名字。 有沒有辦法做到這一點?
UPDATE
這就是我目前的解決方案,我從鏈接的幫助下通過virusstorm
[ComplexType]
public class DateTimeRange
{
[Required]
public DateTime From { get; set; }
public DateTime? To { get; set; }
}
,然後提供了,在的DbContext類:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Types<Article>().Configure(config => config.Property(article => article.Published.From).HasColumnName("PublishedFrom"));
modelBuilder.Types<Article>().Configure(config => config.Property(article => article.Published.To).HasColumnName("PublishedTo"));
}
看看代碼優先的自定義約定。 –