【问题标题】:How to map properties in EF CTP5如何在 EF CTP5 中映射属性
【发布时间】:2010-12-17 13:27:45
【问题描述】:

在 CTP 4 中,我们可以像这样选择要映射的属性:

    this.MapSingleType(i => new
{
    i.Id,
    i.OriginalFileName,
    i.Extension,
    i.MimeType,
    i.Width,
    i.Height,
    i.ImageStoreLocationId,
    i.AlternateText,
    i.ImageData
});

我们如何在 CTP5 中实现这一点?

我尝试使用以下 Map 配置,但这似乎不起作用,因为我仍然必须明确忽略 (this.Ignore(..)) 我不想映射的属性:

    Map(config =>
{
    config.Properties(i => new
    {
        i.OriginalFileName,
        i.Extension,
        i.MimeType,
        i.Width,
        i.Height,
        i.ImageStoreLocationId,
        i.AlternateText,
        i.ImageData
    });

    config.ToTable("Images");
});

考虑到新的API应该更流畅,奇怪的是我必须编写更多的代码来实现同样的事情。

谢谢 本

【问题讨论】:

    标签: entity-framework-4 entity-framework-ctp5


    【解决方案1】:

    这篇博文有 ctp 5 映射示例。

    http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-fluent-api-samples.aspx

    需要一个 clr-nullable 属性:

    modelBuilder.Entity<Product>() 
        .Property(p => p.Name) 
        .IsRequired();
    

    更改字符串长度:

    modelBuilder.Entity<Product>() 
        .Property(p => p.Name) 
        .HasMaxLength(50);
    

    关闭身份:

    modelBuilder.Entity<Product>() 
        .Property(p => p.ProductId) 
        .HasDatabaseGenerationOption(DatabaseGenerationOption.None);
    

    忽略一个属性:

    modelBuilder.Entity<Person>() 
        .Ignore(p => p.Name); 
    

    表和列映射 更改列名:

    modelBuilder.Entity<Category>() 
        .Property(c => c.Name) 
        .HasColumnName("cat_name");
    

    更改表名:

    modelBuilder.Entity<Category>() 
        .ToTable("MyCategories");
    

    使用架构更改表名:

    modelBuilder.Entity<Category>() 
        .ToTable("MyCategories", "sales");
    

    【讨论】:

    • 是的,我看过这篇文章,但它没有解释如何映射一组属性。在这种情况下,我不想依赖约定来映射我的班级。
    • 不确定您所说的一组属性是什么意思?如果您需要映射属性,新的 api 是 modelBuilder.Entity() .Property(c => c.Name) .HasColumnName("cat_name");
    【解决方案2】:

    CTP5 在 Data Annotations 和 Fluent API 方面确实更加强大和灵活。例如,在 CTP4 中,如果我们想从映射中排除一个属性,我们必须用 MapSingleType 显式映射 everything else 以跳过我们不想要的属性,例如你提到的方式。
    在 CTP5 中,这可以简单地通过在属性上使用 [NotMapped] 属性或通过这个流畅的 API 代码来完成:

    this.Ignore(i => i.Id);
    

    你已经完成了,不需要调用Map方法。

    【讨论】:

    • 是的,我意识到我可以忽略这样的属性。我可以不再像以前那样映射一组属性吗?在某些情况下,这比依赖惯例更可取。
    • 啊,现在我明白你的意思了。是的,您是对的,似乎您必须明确忽略该属性,否则它会抱怨。拥有[NotMapped] 属性,恕我直言,这还不错。
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多