33

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?

1

4 Answers 4

79

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

[NotMapped]        
public string AddressAs { get; set; }
0
34

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);
3
  • 2
    Or in VB builder.Entity(Of Employee).Ignore(Function(e) e.AddressAs)
    – Michal B.
    May 23, 2012 at 8:54
  • 4
    Would this be global? I mean, what if I want to do it for just this one call? Can I turn it back on, so to speak?
    – vbullinger
    Apr 8, 2013 at 14:10
  • Yes still useful. you just saved me 40 minutes of research.
    – demo.b
    Aug 30, 2015 at 14:31
21

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

3
  • 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: blogs.msdn.com/efdesign/archive/2009/10/12/…
    – Yogesh
    Nov 30, 2009 at 4:25
  • Would be a real bonus if they add a .Exclude() Jun 11, 2015 at 20:32
  • Is there a way to exclude a particular field from all classes in a model using the T4 template? Aug 29, 2016 at 2: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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.