【问题标题】:EF Code First: Map only one property while leaving other properties as defaultEF Code First:仅映射一个属性,而将其他属性保留为默认值
【发布时间】:2015-08-21 08:19:18
【问题描述】:

我的课程 Product 有 20 多个属性。我只想将Picture 映射到另一个表,让其他人映射到表Product

class Product
{
   public int Id {get; set;}
   public byte[] Picture {get; set;}
   ...
   ...
}

我知道的唯一方法是通过ModelBuilder

modelBuilder.Entity<Product>()
                .Map(m =>
                         {
                             m.Property(p => p.Picture);
                             m.ToTable("ProductPic");
                         })
                .Map(m =>
                        {
                             // All other properties here:
                             m.Property(p => p.Id);
                             m.ToTable("Product");
                             // But there are too many!!!
                        });

如上所示,映射所有其他属性很繁琐。有没有什么办法可以排除一个属性走不同的路而让其他的遵循默认?

【问题讨论】:

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


    【解决方案1】:

    这种语法会减轻一点痛苦:

    modelBuilder.Entity<Product>()
        .Map(m =>
        {
           m.Properties(p => new
           {
               p.Picture
           });
           m.ToTable("ProductPic");
        }
        .Map(m =>
        {
           m.Properties(p => new
           {
               p.Field1,
               p.Field2,
               ...
               p.Fieldn
           });
           m.ToTable("Product");
        }
    

    不需要映射ID和ToTable()只指定一次。

    【讨论】:

    • 谢谢,但您知道只有一个属性不会产生太大变化
    • 我明白了。另一种选择是做你自己的 T4 模板,如果你做很多这些,它会有所帮助。有点学习曲线。 msdn.microsoft.com/en-us/library/bb126445.aspx
    猜你喜欢
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 2013-05-21
    • 2016-03-16
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多