Map only the selected columns when using EntityFramework

Nuwan Wickramanayaka 21 Reputation points
2022-09-23T17:53:48.407+00:00

In my recent Entity Core project I am having database table called "YmPlant" and it has 20+ columns. But for my requirement I just need data only from 3 columns. Also I am not required to do the write operations. Only read from YmlPlant table.

Just I need to know is it required to map all columns (20 +) inside the "OnModelCreating" method for YmlPlant table. Either it is working with mapping only the required 3 columns ?

Thanks
Nuwan

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
701 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,455 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,370 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Laxmikant 216 Reputation points
    2022-09-23T21:05:15.04+00:00

    on model class you can use attribute

     [NotMapped]  
     public int ProductDiscountValue { get; set; }      
    

    or on model binding event use Fluent API to ignore not required columns

    protected override void OnModelCreating(ModelBuilder modelBuilder)  
    {  
        modelBuilder.Entity<ymlPlant>()  
           .Ignore(t => t.columnname);        
    }  
    

    see more on EF Core Fluent API

    0 comments No comments

  2. Karen Payne MVP 35,201 Reputation points
    2022-09-24T19:45:34.407+00:00

    As @AgaveJoe indicated create a class with that is needed e.g. I have a Customer model and to get only what is needed I created CustomerItem which in turn we use the following to get data back,

    public static async Task<List<CustomerItem>> CustomerItems()  
    {  
        await using var context = new Context();  
        return await context.Customers.AsNoTracking().Select(x => new CustomerItem()  
        {  
            CustomerIdentifier = x.CustomerIdentifier,   
            CompanyName = x.CompanyName,  
            ContactId = x.ContactId  
        }).ToListAsync();  
    }  
    
    0 comments No comments