Hans
Hans

Reputation: 2832

EF Code First: Map only one property while leaving other properties as default

I have class Product with more than 20 properties. I want to map only Picture to another table and leave others to get mapped to the table Product.

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

The only way I know is through 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!!!
                        });

As shown above, mapping all other properties is tedious. Is there any way to exclude just one property to go different way and leave other follow the default?

Upvotes: 0

Views: 60

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

This syntax would ease the pain a bit:

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

Don't need to map the ID and ToTable() only specified once.

Upvotes: 1

Related Questions