VS2013上使用EF Power Tools的Reverse Engineer Code First逆向生成Model时,没有处理计算字段。在保存实体时会出现错误。
可以通过修改Mapping.tt解决。
打开Mapping.tt,找到
foreach (var prop in efHost.EntityType.Properties) { var type = (PrimitiveType)prop.TypeUsage.EdmType; var isKey = efHost.EntityType.KeyMembers.Contains(prop); var storeProp = efHost.PropertyToColumnMappings[prop]; var sgpFacet = storeProp.TypeUsage.Facets.SingleOrDefault(f => f.Name == "StoreGeneratedPattern"); var storeGeneratedPattern = sgpFacet == null ? StoreGeneratedPattern.None : (StoreGeneratedPattern)sgpFacet.Value; var configLines = new List<string>(); if (type.ClrEquivalentType == typeof(int) || type.ClrEquivalentType == typeof(decimal) || type.ClrEquivalentType == typeof(short) || type.ClrEquivalentType == typeof(long)) { if (isKey && storeGeneratedPattern != StoreGeneratedPattern.Identity) { configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)"); } else if ((!isKey || efHost.EntityType.KeyMembers.Count > 1) && storeGeneratedPattern == StoreGeneratedPattern.Identity) { configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)"); } }
在 var configLines = new List<string>(); 后添加计算字段的内容:
foreach (var prop in efHost.EntityType.Properties) { var type = (PrimitiveType)prop.TypeUsage.EdmType; var isKey = efHost.EntityType.KeyMembers.Contains(prop); var storeProp = efHost.PropertyToColumnMappings[prop]; var sgpFacet = storeProp.TypeUsage.Facets.SingleOrDefault(f => f.Name == "StoreGeneratedPattern"); var storeGeneratedPattern = sgpFacet == null ? StoreGeneratedPattern.None : (StoreGeneratedPattern)sgpFacet.Value; var configLines = new List<string>(); if(!isKey && storeGeneratedPattern == StoreGeneratedPattern.Computed) { configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)"); } if (type.ClrEquivalentType == typeof(int) || type.ClrEquivalentType == typeof(decimal) || type.ClrEquivalentType == typeof(short) || type.ClrEquivalentType == typeof(long)) { if (isKey && storeGeneratedPattern != StoreGeneratedPattern.Identity) { configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)"); } else if ((!isKey || efHost.EntityType.KeyMembers.Count > 1) && storeGeneratedPattern == StoreGeneratedPattern.Identity) { configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)"); } }
再次使用Reverse Engineer Code First。
得到带计算字段信息的mapping。
this.Property(t => t.ResetDate) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed); this.Property(t => t.ResetHour) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);