elena-kim / study-efcore

Study EntityFramework Core

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Docs

  • Ignoring a class property in Entity Framework 4.1 Code First

    NotMapped Attribute

    public class Customer
    {
        public int CustomerID { set; get; }
        public string FirstName { set; get; } 
        public string LastName { set; get; } 
        [NotMapped]
        public int Age { set; get; }
    }

    OnModelCreating function

    public class SchoolContext : DbContext
    {
        public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
        {
        }
        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
            base.OnModelCreating(modelBuilder);
        }
        
        public DbSet<Customer> Customers { get; set; }
    }

  • Entity Framework Extensions

    UpdateFromQuery

    // UPDATE all customers that are inactive for more than two years
    var date = DateTime.Now.AddYears(-2);
    context.Customers
        .Where(x => x.IsActive && x.LastLogin < date)
        .UpdateFromQuery(x => new Customer {IsActive = false});
    
    // UPDATE customers by id
    context.Customers.Where(x => x.ID == userId).UpdateFromQuery(x => new Customer {IsActive = false});

    DeleteFromQuery

    // DELETE all customers that are inactive
    context.Customers.Where(x => !x.IsActive).DeleteFromQuery();
    
    // DELETE customers by id
    context.Customers.Where(x => x.ID == userId).DeleteFromQuery();

    Performance Comparisons

    Operations 1,000 Entities 2,000 Entities 5,000 Entities
    SaveChanges 1,000 ms 2,000 ms 5,000 ms
    UpdateFromQuery 1 ms 1 ms 1 ms
    DeleteFromQuery 1 ms 1 ms 1 ms

About

Study EntityFramework Core

License:MIT License