Udostępnij za pośrednictwem


Tip 46 – How to exclude a property using Code-Only

This time a real simple one prompted by this question on StackOverflow.

Problem:

If you tell the Entity Framework about this class using Code-Only, by default every property becomes part of Entity, and as a result stored in the database.

Usually this is what you want.

But not always, imagine this class:

public class Person{
public int ID {get;set;}
public string Firstname {get;set;}
public string Surname {get;set;}
public string Fullname {get;set;}
}

Here Fullname is actually just the Firstname and Surname concatenated together, so storing the Fullname separately in the database would be redundant. You really want to ignore Fullname.

So how do you do that?

Solution 1 – Remove Setter – aka ‘generally not an option’

To be a property of the ‘Entity’, the Entity Framework must be-able to read & write the property, so if you remove the setter, the CLR property is no longer an ‘Entity’ property.

Unfortunately it isn’t always possible to do this sort of thing, and more importantly doing something like this *just* to work with Code-Only and EF is the opposite of persistence ignorance!

We need another solution…

Solution 2 – Map all the properties you want explicitly

If you explicitly map, rather than allowing Code-Only to map by convention, properties you omit from the mapping are ignored.

So this mapping:

builder.Entity<Person>().MapSingleType(p => new {
p.ID,
p.Firstname,
p.Surname
});

along with specifying the mapping has a side-effect of telling Code-Only to ignore the FullName property.

Longer term solution?

Now obviously being forced to map every other property *just* to exclude one property is not an ideal solution, especially if everything else is ‘by convention’.

Something like this would be better:

builder.Entity<Person>().Exclude(p => p.Fullname);

This isn’t currently supported, in CTP 2 for Beta2, but it is being considered for future versions of Code-Only…

Comments

  • Anonymous
    November 29, 2009
    I'm glad to see that this is being considering for the next version of Code-only. I'd like to pass my opinion along to you and the team that the Exclude() method would definitely be considered an important and helpful feature by developers like me.As a side note, keep up the great job on the helpful blog posts.