Entity Framework, Let's add some power to it

 

Wow Entity Framework is starting to pack Power

So, what do I mean by that. It was released 15 years ago on the 11 of August 2008. Back then it was part of the .NET Framework 3.5 Service Pack 1  and you could use it with Visual Studio 2008 as long as you had service pack 1. To be honest, back then it wasn't very good. It was slow and a little painful. Jump forward 15 years...

Jump forward 16 years and we now have Entity Framework Core 9. You can add it to you use it .Net 9 as a set of Nuget packages.  This short blog post isn't going to teach you how to use EF Core 9, or .Net 9 it is simply going to show you how to ramp up your retrieval of data.

So, why is EF 9 Core so powerful?

Say we have a service Method called CreateBankCustomer that accept a complex object that includes BankCustomer and a list of BankBankAccounts? You can create all the table entries in one fail swoop....

using (var context = new BankingContext())
{
    var customer = new BankCustomer
    {
        BankId = 1,
FirstName = "Andy",
LastName = "Tate",
        BankBankAccounts = new List<BankBankAccount>
        {
            new BankBankAccounts { AccountType = "Checking", RoutingCode="123453585", AccountNumber="73287873287287", OpeningBalance=100.00 },
            new BankBankAccounts {  AccountType = "Savings", RoutingCode="123453585", AccountNumber="73285345435545", OpeningBalance=50.00 },
        }
    };

    context.BankCustomers.Add(customer);
    context.SaveChanges();
}

In this example I am hard coding the children but if you were passed customer and it had the child entities then you would simply need to do

public int AddBankCustomer(BankCustomer customer) {
    using (var context = new BankingContext())
    {
        context.BankCustomers.Add(customer);
        context.SaveChanges();
    }
    return customer.Id;
}

Now, that is a bit easier than calling Create on a BankCustomer then Create on BankBankAccount twice.

How about getting the data?

using (var context = new BankingContext())
 {
    var customer =  _db.BankCustomer.Include(customer => customer.BankBankAccounts).FirstOrDefault(u => u.Id == id);
}

Now the best thing that they have added... What if I only want the customer and their savings account...

var customer =  _bankDbContext.BankCustomers.Include(customer => customer.BankBankAccounts.Where(bc => bc.AccountType == "Savings")).FirstOrDefault(u => u.Id == id);

So, now you see the power of Entity Framework. 

One final thing... on updating data with EF 9 Core, it is smart enough to see what has changed and only ask the database to update that column(s).

Comments

Popular posts from this blog

When Greed and Deception Destroy a Company

Let's Geocode with Here.com

I am Me, no excuses, just Me