EF Code First子类中的实体列

时间:2017-08-04 11:44:12

标签: c# entity-framework ef-code-first

我正在尝试使用EF Code First并创建了实体Article

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

但是,我希望在没有下划线的情况下生成列名。我尝试提供列FromTo特定名称:

[Required, Column("PublishedFrom")]
public DateTime From { get; set; }

[Column("PublishedTo")]
public DateTime? To { get; set; }

完美运作:

PublishedFrom = c.DateTime(nullable: false),
PublishedTo = c.DateTime()

事情就是:就像我说的那样,我想在同一个实体中使用多个实体甚至多次,因此在DateTimeRange中给出固定名称是行不通的。我更喜欢能够说没有下划线来连接名称。 有没有办法做到这一点?

更新
这是我目前使用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"));
}

1 个答案:

答案 0 :(得分:1)

You need to make DateTimeRange a complex type in Entity Framework with an attribute. You will then need to add setup details in the OnModelCreating method. Take a look at Making Complex Types Useful with Entity Framework 6 Custom Configurations. This should set you down the right path.