Benk
Benk

Reputation: 1312

Entity Framework 4.1 & existing database

Hi I have an existing database with a table with 30 fields, I want to split the table into many models so I could retrieve/save fields that I need and not every time retrieve/save the whole object from the db. using c#.

I think I should be using Code-First. Could someone provide an example or a tutorial link?

thanks,

Upvotes: 0

Views: 162

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

You don't need to split table to be able to load a subset of field or persist subset of fields. Both operations are available with the whole table mapped to single entity as well.

For selection you simply have to use projection:

var data = from x in context.HugeEntities
           select new { x.Id, x.Name };

You can use either anonymous type in projection or any non-mapped class.

For updates you can simply use:

var data = new HugeEntity { Id = existingId, Name = newName };
context.HugeEntities.Attach(data);
var dataEntry = context.Entry(data);
dataEntry.Property(d => d.Name).IsModified = true; // Only this property will be updated
context.SaveChanges();

Or:

var data = new HugeEntity { Id = existingId };
context.HugeEntities.Attach(data);
data.Name = newName; 
context.SaveChanges(); // Now EF detected change of Name property and updated it

Mapping multiple entities to single table must follows very strict rules and it is possible only with table splitting were all entities must be related with one-to-one relation (and there are some problems with more than two entities per split table in code first) or with table-per-hierarchy inheritance. I don't think that you want to use any of them for this case.

Upvotes: 1

Related Questions