Exclude a field/property from the database with Entity Framework 4 & Code-First

后端 未结 4 1017
悲&欢浪女
悲&欢浪女 2020-11-29 04:24

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          


        
相关标签:
4条回答
  • 2020-11-29 05:05

    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);
    
    0 讨论(0)
  • 2020-11-29 05:16

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

    [NotMapped]        
    public string AddressAs { get; set; }
    
    0 讨论(0)
  • 2020-11-29 05: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

    0 讨论(0)
  • 2020-11-29 05:27

    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);
    
    0 讨论(0)
提交回复
热议问题