Csharp/C#教程:忽略Entity Framework 6中的所有属性,但忽略一些属性分享


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

我想使用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; } } 

而你只想存储IdSomeSpecialId ,你会这样做:

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

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

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

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

这是您的IgnoreAllBut方法:

 public static EntityTypeConfiguration IgnoreAllBut(this EntityTypeConfiguration entityTypeConfiguration, params Expression>[] 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>(expression, param); entityTypeConfiguration.Ignore(result); } return entityTypeConfiguration; } 

您可以在类本身中将单个属性标记为NotMapped。

 public class MyPoco { public int Id { get; set; } [NotMapped] public string Name { get; set; } public int SomeSpecialId { get; set; } } 

不解决你的问题’忽略除了这一切之外的一切’,但可能会明显包括什么和不包括在内。

上述就是C#学习教程:忽略Entity Framework 6中的所有属性,但忽略一些属性分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/983469.html

(0)
上一篇 2021年12月19日
下一篇 2021年12月19日

精彩推荐