C# / .NETDevOpsMisc
C# / .NET
Mapping database objects to models - the Lambda way
Alexandru Puiu
Alexandru Puiu
April 26, 2013
1 min

Updated with statements that can be executed or deferred.

// Example models
public class SomeModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List Items { get; set; }
}
public class SomeOtherModel
{
    public int Id { get; set; }
    public string Text { get; set; }
}
//Expression mapper - not executed
public Expr<Func> Map_SomeTable_SomeModel_Expr()
{
    return x => new SomeModel
    {
        Id = x.Id,
        Name = x.Name,
        Items = db.SomeOtherTable.Where(y => y.SomeTableId == x.Id).Select(Map_SomeOtherTable_SomeOtherModel_Expr()).ToList()
    }
}
//Function mapper - compiled and makes the query execute;
//    can also be obtained by calling Compile() on an expression;
//    can be called as a function
public Func Map_SomeTable_SomeModel_Func = x => new SomeModel
{
    Id = x.Id,
    Name = x.Name,
    Items = db.SomeOtherTable.Where(y => y.SomeTableId == x.Id).Select(Map_SomeOtherTable_SomeOtherModel_Func()).ToList()
};
public Expr<Func> Map_SomeOtherTable_SomeOtherModel_Expr()
{
    return x => new SomeOtherModel
    {
        Id = x.Id,
        Text = x.Text
    }
}
public Func Map_SomeOtherTable_SomeOtherModel_Func = x => new SomeOtherModel
{
    Id = x.Id,
    Text = x.Text
};
//Example repository method
public List GetAllSomeModels()
{
    var query = db.SomeTable.Select(Map_SomeTable_SomeModel_Expr()); // Is saved as query and not executed
    var model = db.SomeTable.Select(Map_SomeTable_SomeModel_Func); // Query is executed and result set is returned
}

Tags

utils
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

RavenDB Integration Testing
Using RavenDB in Integration Testing
December 24, 2022
2 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media