powlette
powlette

Reputation: 1800

Entity Framework 4.1 with existing classes AND existing tables

I have a large set of classes implementing business logic. Most have a .Load method that uses plain old ADO.net to read values from Sql Server that I've written by hand over the years. This all predates Linq2Sql and EF.

Now I want to update my class library to use Entity Framework but I'd like to do it as painlessly as possible. I've learned EF can infer column and key names from property names in my classes, but my classes have many properties that don't correspond to column names and some properties that don't match the database's column names. I'd prefer not to have to .Ignore() each of those properties (and remember to always .Ignore() any future properties) and .HasColumnName() all the differences.

What's the easiest way to use EF with existing tables AND existing classes so I can do minimal mappings and still use a DbContext to .Find() an entity and SaveChanges() and all the other nice strongly-typed things EF supports without going through all my business classes by hand and annotating which properties to include?

For example, I'd expect to be able to db.Customers.Find(123) and have it create a Customer instance, select * from customers where CustomerID=123, and map the columns that DO exist to the properties that DO exist as best as possible and give me a ready to use Customer instance and then I can annotate any differences as needed. Is this possible or am I asking too much of EF?

Is there maybe a smarter DbContext that will make a best effort to map properties so I can leverage all my existing business classes? Maybe I should consider some other ORM?

Upvotes: 1

Views: 836

Answers (2)

user1235486
user1235486

Reputation: 51

Try this: create a data model (.edmx) from your database. edit the model, Adding property and procedures of your Class That You want to add to the database. Finally, update your database from your model (.Edmx) Selecting only the tables and procedures exist That You Have changes. You can look at those tutorials http://msdn.microsoft.com/en-us/data/gg685494 http://msdn.microsoft.com/en-us/data/gg685489

Upvotes: 1

Marcus
Marcus

Reputation: 2480

EF4 “Code First” enables you to optionally override its default database persistence mapping rules, and configure alternative ways to map your classes to a database.

There are a few ways to enable this. One of the easiest approaches is to override the “OnModelCreating” method defined on the DbContext base class:

public class YourContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Mapping
    }
}

You can still search your entities by Primary Key by using Find:

var unicorn = context.Unicorns.Find(3);

Upvotes: 0

Related Questions