34

I will like to know that is there a way to exclude some fields from the database? For eg:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FatherName { get; set; }

    public bool IsMale { get; set; }
    public bool IsMarried { get; set; }

    public string AddressAs { get; set; }
}

How can I exclude the AddressAs field from the database?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Yogesh
  • 14,498
  • 6
  • 44
  • 69
  • Possible duplicate of [Ignoring a class property in Entity Framework 4.1 Code First](http://stackoverflow.com/questions/10385248/ignoring-a-class-property-in-entity-framework-4-1-code-first) – Michael Freidgeim Aug 26 '16 at 05:14

4 Answers4

80

for future reference: you can use data annotations MSDN EF - Code First Data Annotations

[NotMapped]        
public string AddressAs { get; set; }
Martin
  • 5,165
  • 1
  • 37
  • 50
markwilde
  • 1,892
  • 1
  • 16
  • 23
35

I know this is an old question but in case anyone (like me) comes to it from search...

Now it is possible in entity framework 4.3 to do this. You would do it like so:

builder.Entity<Employee>().Ignore(e => e.AddressAs);
kmp
  • 10,535
  • 11
  • 75
  • 125
22

In the current version the only way to exclude a property is to explicitly map all the other columns:

builder.Entity<Employee>().MapSingleType(e => new {
  e.Id,
  e.Name,
  e.FatherName,
  e.IsMale,
  e.IsMarried
});

Because AddressAs is not referenced it isn't part of the Entity / Database.

The EF team is considering adding something like this:

builder.Entity<Employee>().Exclude(e => e.AddressAs);

I suggest you tell leave a comment on the EFDesign blog, requesting this feature :)

Hope this helps

Alex

Alex James
  • 20,874
  • 3
  • 50
  • 49
  • 3
    I realized that the only way to do it as of today is the way you mentioned. I posted it on EFDesign blog a long back: http://blogs.msdn.com/efdesign/archive/2009/10/12/code-only-further-enhancements.aspx – Yogesh Nov 30 '09 at 04:25
  • Would be a real bonus if they add a `.Exclude()` – Zapnologica Jun 11 '15 at 20:32
  • Is there a way to exclude a particular field from all classes in a model using the T4 template? – Bat_Programmer Aug 29 '16 at 02:03
0

It's also possible to add the column you want to ignore as a Shadow Property in the DbContext:

builder.Entity<Employee>().Property<string>("AddressAs");

Then you can query on that column like so:

context.Employees.Where(e => EF.Property<string>(e, "AddressAs") == someValue);
Willem Ellis
  • 4,886
  • 7
  • 38
  • 55