改变EF6转换为bool的源代码 [英] Changing EF6 source code for conversion of short to bool

查看:158
本文介绍了改变EF6转换为bool的源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果布尔目的地属性标有一个或多个值,那么修改映射代码可以将值为零或非零的 short 转换为false或true属性在POCO模型中?



我的意思是,这应该是EF是开源的优点之一,只能在内部使用。 p>

任何关于代码中哪里的提示将不胜感激,但这个问题真的比较笼统,我想听到任何人都不得不说的话。 / p>

解决方案

关于一般性意见,请。
我不知道使EF改变,但处理类似问题在EF中并不罕见。
EF不支持所有标准类型。



你可以在你的POCO类中有一个帮助字段。
所以一个字段是实际的DB字段,但没有在POCO外部使用。
帮助字段在流畅的API中是NOTMAPPED或忽略的。
您可以通过助手访问数据库,并执行任何所需的转换。
一个简单的例子。或者反过来,如果我有帮助和DB字段类型回到前面。

  [NotMapped] 
public virtual bool IsVisible {set;得到; } // Helper Field NOT on DB
public int Test {get {return IsVisible? 1:0; } //在DB上,但是只能通过帮助来设置和获取。
set {IsVisible =(value!= 0);

编辑:Power Fluent API
这是一个这段代码描述了如何以一致的方式为每个映射的poco运行代码。

  public class MyDbContext:DbContext 
//建立模型,设置断点,以便您知道何时触发
//这个ISNT很重要,每次只能在模型缓存上调用。
//在我的情况下是应用程序池回收。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
//使用CONFIG添加功能更好地组织并允许在映射时使用继承
//我将使用片段和静态把事情简单化。
modelBuilder.Configurations.Add(XYZMap.Map()); // POCO map
modelBuilder.Configurations.Add(ABCMAP.Map()); // poco map
modelBuilder.Configurations.Add(XXXMap.MAP()); // poco map
// etc for your POCO set
//注意,不需要声明DBset< xyz> XYZs {get; set;} !!!!

public static class XYZMap {
public static BaseEntityIntConfiguration< PocoXYZ> Map(){
//查看返回对象!
var entity = new BaseEntityLongConfiguration< PocoXYZ>();
//entity.Property()... //像往常一样映射POCO specifc
///entity.HasRequired()...// property and relationships as required
//对于默认的
返回实体不做任何事情;
}
}
}


//所有具有int键的表都使用此基本配置。做一次再一次
public class BaseEntityIntConfiguration< T> :BaseEntityConfiguration< T>其中T:BaseObjectInt {
public BaseEntityIntConfiguration(DatabaseGeneratedOption DGO = DatabaseGeneratedOption.Identity){
//主键
this.HasKey(t => t.Id);

//属性
// Id是由DB
分配的int this.Property(t => t.Id).HasDatabaseGeneratedOption(DGO); //默认为db生成
//乐观锁也被添加到这里,具体到out poco设计
this.Property(t => t.RowVersion)
.IsRequired()
.IsFixedLength()
.HasMaxLength(8)
.IsRowVersion();

//任何其他常见的映射/规则?

}
}

public class BaseEntityConfiguration< T> :EntityTypeConfiguration< T>其中T:BaseObject {
public BaseEntityConfiguration(){
this.ApplyAttributeRules(); //<<<<这里是我应用SYSTEM WIDE规则的地方
}
}


public static void ApplyAttributeRules< T>(此EntityTypeConfiguration&T;实体)其中T:BaseObject {
//所以这将被调用每个映射类型

foreach(var propertyInfo in typeof(T).GetProperties()){
//我用反射来寻找属性符合某些标准。
//例如string。我想要NVARCHAR 4000不是NVCAHR max,所以我可以索引它。
if(propertyInfo.UnderLyingType()。FullName ==System.String){
SetStringLength(BosTypeTool.StringLengthIndexable,propertyInfo.Name,entity);
继续;
}

SetStringLength(4000,propertyInfo.Name,entity);

}

}
private static void SetStringLength< TModelPoco>(int length,string propertyName,
EntityTypeConfiguration< TModelPoco>实体)其中TModelPoco:BaseObject {
var propLambda = DynamicExpression.ParseLambda< TModelPoco,String>(propertyName);
entity.Property(propLambda).HasMaxLength(length);
//来自Microsoft的动态库.... http://msdn.microsoft.com/en-US/vstudio/bb894665.aspx
}
//获取底层类型它是nullable
public static Type UnderLyingType(this PropertyInfo propertyInfo){
return Nullable.GetUnderlyingType(propertyInfo.PropertyType)? propertyInfo.PropertyType;
}


What is the feasibility of modifying the mapping code to convert a short of value zero or non-zero to false or true, if the boolean destination property is marked with an attribute in the POCO model?

I mean, this is supposed to be one of the advantages of EF being open sourced, and would be for in house use only.

Any tips on where in the code I would look would be appreciated, but this question is really more general and I'd like to hear anything anyone has to say on this.

解决方案

With regard to the General comments please. I dont know to make the EF change, but dealing with similar issues is not an uncommon issue in EF. Not all standard types are supported by EF.

You can have a helper field in your POCO class. So one field is the actual DB field, but no used outside of POCO. The help field is NOTMAPPED or ignored in fluent API. You access the DB via you helper and execute any required casting. A simple example. Or the reverse if I got helper and DB field types back to front.

   [NotMapped]
    public virtual bool IsVisible { set; get; }  // Helper Field NOT on DB
    public int Test { get { return IsVisible ? 1 : 0; } //  on DB, but set and get via helper only.
                      set { IsVisible = (value != 0); }  }

Edit: Power Fluent API Here is a snippet that outlines how you have code that runs for every mapped poco in a consistent way.

 public class MyDbContext : DbContext 
// model building, set breakpoint so you know when this is triggered   
// it is important this ISNT called everytime, only on model cache.
// in my case that is app pool recycle.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    // use the CONFIG add feature to better organize and allow use of inheritance when mapping
    // I will use snippets and statics to keep it simple. 
        modelBuilder.Configurations.Add(XYZMap.Map()); //  POCO map 
        modelBuilder.Configurations.Add(ABCMAP.Map()); //  poco map
        modelBuilder.Configurations.Add(XXXMap.MAP()); //  poco map
    // etc for your POCO set
    // Note, no need to declare DBset<xyz> XYZs {get;set;} !!!!

     public static class XYZMap {
    public static BaseEntityIntConfiguration<PocoXYZ> Map() {
        //see return object !
        var entity = new BaseEntityLongConfiguration<PocoXYZ>();
         //entity.Property()...   // map away as usual POCO specifc
        ///entity.HasRequired()...// property and relationships as required
                                  // do nothing for default
        return entity;
       }
    }
}


 // all tables with int key use this base config. do it once never again
 public class BaseEntityIntConfiguration<T> : BaseEntityConfiguration<T> where T : BaseObjectInt {
    public BaseEntityIntConfiguration(DatabaseGeneratedOption DGO = DatabaseGeneratedOption.Identity) {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        //Id is an int allocated by DB
        this.Property(t => t.Id).HasDatabaseGeneratedOption(DGO); // default to db generated
        // optimistic lock is also added here, Specific to out poco design
        this.Property(t => t.RowVersion)
            .IsRequired()
            .IsFixedLength()
            .HasMaxLength(8)
            .IsRowVersion();

        // any other common mappings/ rules ?? 

    }
}

   public class BaseEntityConfiguration<T> : EntityTypeConfiguration<T> where T : BaseObject {
    public BaseEntityConfiguration() {
            this.ApplyAttributeRules();   // <<<<< Here is where I apply SYSTEM WIDE rules
    }
}


  public static void ApplyAttributeRules<T>(this EntityTypeConfiguration<T> entity) where T : BaseObject {
  // so this will be called for each mapped type

   foreach (var propertyInfo in typeof (T).GetProperties()) {
       // I use reflection to look for properties that meet certain criteria.
       // eg string.  I want as NVARCHAR 4000 not NVCAHR max so i can index it.
      if (propertyInfo.UnderLyingType().FullName == "System.String") {
                    SetStringLength(BosTypeTool.StringLengthIndexable, propertyInfo.Name, entity);
                    continue;
                }  

        SetStringLength(4000, propertyInfo.Name, entity); 

   }

 }
  private static void SetStringLength<TModelPoco>(int length, string propertyName,
        EntityTypeConfiguration<TModelPoco> entity) where TModelPoco : BaseObject {
        var propLambda = DynamicExpression.ParseLambda<TModelPoco, String>(propertyName);
        entity.Property(propLambda).HasMaxLength(length);
  // dynamic library from Microsoft.... http://msdn.microsoft.com/en-US/vstudio/bb894665.aspx
    }
 // get underlying type incase it is nullable
 public static Type UnderLyingType(this PropertyInfo propertyInfo) {
        return Nullable.GetUnderlyingType(propertyInfo.PropertyType) ??                  propertyInfo.PropertyType;
    }

这篇关于改变EF6转换为bool的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆