Skip to main content
 首页 » 编程设计

c#之忽略所有属性,但 Entity Framework 6 中的一些属性

2024年02月06日11qq78292959

我想使用 Entity Framework 将一些数据保存在数据库中。
我有一些更大的 POCO,但我只想存储一些属性。

我知道我可以通过 Ignore() 方法使用 Fluent API 实现此目的。但是是否也有可能不仅忽略定义的属性,而且忽略除定义之外的所有属性?
因此,如果您有这样的 POCO:

public class MyPoco 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    . 
    . 
    . 
    public int SomeSpecialId { get; set; } 
} 

如果你只想存储 Id 和 SomeSpecialId,你可以这样做:

protected override void OnModelCreating(DbModelBuilder builder) 
{ 
    builder.Entity<MyPoco>().Ignore(x => x.Name); 
    builder.Entity<MyPoco>().Ignore(x => x.WhatEver); 
    . 
    . 
    . 
    // ignore everything but Id and SomeSpecialId 
    base.OnModelCreating(builder); 
} 

现在的问题是,如果您必须扩展 POCO 但不想保留那些扩展的属性,您还必须更改 OnModelCreating() 方法。那么有没有办法做这样的事情:

public override void OnModelCreating(DbModelBuilder builder) 
{ 
    builder.Entity<MyPoco>().IgnoreAllBut(x => x.Id, x.SomeSpecialId); 
    base.OnModelCreating(builder); 
} 

请您参考如下方法:

您可以编写一个扩展方法来执行此操作。代码并不简单,因为您需要使用表达式树。

这是您的 IgnoreAllBut 方法:

public static EntityTypeConfiguration<T> IgnoreAllBut<T>(this EntityTypeConfiguration<T> entityTypeConfiguration, 
        params Expression<Func<T, object>>[] properties) where T : class 
{ 
    // Extract the names from the expressions 
    var namesToKeep = properties.Select(a => 
    { 
        var member = a.Body as MemberExpression; 
        // If the property is a value type, there will be an extra "Convert()" 
        // This will get rid of it. 
        if (member == null) 
        { 
            var convert = a.Body as UnaryExpression; 
            if (convert == null) throw new ArgumentException("Invalid expression"); 
            member = convert.Operand as MemberExpression; 
        } 
        if (member == null) throw new ArgumentException("Invalid expression"); 
        return (member.Member as PropertyInfo).Name; 
    }); 
    // Now we loop over all properties, excluding the ones we want to keep 
    foreach (var property in typeof(T).GetProperties().Where(p => !namesToKeep.Contains(p.Name))) 
    { 
        // Here is the tricky part: we need to build an expression tree 
        // to pass to Ignore() 
        // first, the parameter 
        var param = Expression.Parameter(typeof (T), "e"); 
        // then the property access 
        Expression expression = Expression.Property(param, property); 
        // If the property is a value type, we need an explicit Convert() operation 
        if (property.PropertyType.IsValueType) 
        { 
            expression = Expression.Convert(expression, typeof (object)); 
        } 
        // last step, assembling everything inside a lambda that 
        // can be passed to Ignore() 
        var result = Expression.Lambda<Func<T, object>>(expression, param); 
        entityTypeConfiguration.Ignore(result); 
    } 
    return entityTypeConfiguration; 
}