Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(五)
直接贴代码了:
NewsInfo 实体类:
public class NewsInfo
{
public int NewsInfoId { get; set; }
public string NewsInfoTitle { get; set; } public int? NewsTypeId { get; set; } public virtual NewsType NewsTypeInfo { get; set; }
}
NewsType 实体类:
public class NewsType
{
public int TypeId { get; set; } //[MaxLength(50)]
public string TypeName { get; set; } /// <summary>
/// 产品列表
/// </summary>
public virtual ICollection<NewsInfo> NewsInfoList { get; set; }
}
NewsInfoMap 实体映射类(利用 EF Fluent API 注册)
public class NewsInfoMap : EntityTypeConfiguration<NewsInfo>
{
public NewsInfoMap()
{
this.ToTable("NewsInfos"); // Primary Key
this.HasKey(t => t.NewsInfoId); // Properties
this.Property(t => t.NewsInfoId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.NewsInfoTitle).HasColumnName("Title")
.IsRequired()
.HasMaxLength(); // Relationships
this.HasRequired(n => n.NewsTypeInfo)
.WithMany(t => t.NewsInfoList)
.HasForeignKey(t => t.NewsTypeId)
.WillCascadeOnDelete(false);
}
}
NewsTypeMap 实体映射类(利用 EF Fluent API 注册)
public class NewsTypeMap : EntityTypeConfiguration<NewsType>
{
public NewsTypeMap()
{
this.ToTable("NewsTypes"); // Primary Key
this.HasKey(t => t.TypeId); // Properties
this.Property(t => t.TypeId).HasColumnName("NewsTypeId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.TypeName).HasColumnName("NewsTypeName")
.HasMaxLength();
}
}
NewContext
public class NewContext : DbContext
{
static NewContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NewContext>()); // 架构改变,自动删除,并新建数据库
} public DbSet<NewsInfo> NewsInfos { get; set; }
public DbSet<NewsType> NewsTypes { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new NewsInfoMap());
modelBuilder.Configurations.Add(new NewsTypeMap());
}
}
实际测试:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using CodeFirstDemo.Extensions;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using static CodeFirstDemo.Extensions.MetaHelper; namespace CodeFirstDemo
{
class Program
{
static void Main(string[] args)
{
using (var db = new NewContext())
{
//TestInsertAndQuery(db);
TestGetDbContextMetaInfo(db); Console.ReadKey();
}
} static void TestInsertAndQuery(NewContext db)
{
Console.Write("Please Input News Type Title: ");
var name = Console.ReadLine(); var type_Model = new NewsType { TypeName = name };
db.NewsTypes.Add(type_Model);
db.SaveChanges(); Console.Write("Please Input Search Type Name : ");
var search_type = Console.ReadLine();
var query = from b in db.NewsTypes
where b.TypeName == search_type
select b; Console.WriteLine("Query Result:");
foreach (var item in query)
{
Console.WriteLine(item.TypeName);
}
Console.WriteLine("\n\n\n");
} static void TestGetDbContextMetaInfo(NewContext db)
{
Console.WriteLine("DbContext Meta: \n"); // 测试环境:Win10、SQL Server Express 2008、EntityFramework.6.1.0
// 经过实际测试,下面的所有代码,只有在第一个调用 db.GetTableName<NewsInfo>(); 才会比较慢,因为这
// 时候 EF 会从数据库中拿数据,后面的第二个(db.GetTableName<NewsType>()) 一直到结束都比较快了。可
// 能是 EF 已经缓存了 EDM 信息,所以就比较快了。 // Table Name
string newsTableName = db.GetTableName<NewsInfo>();
Console.WriteLine("NewsInfo TableName: " + newsTableName); // dbo.NewsInfos string NewTypeTableName = db.GetTableName<NewsType>();
Console.WriteLine("NewsType TableName: " + NewTypeTableName); //dbo.NewsTypes Console.WriteLine("\n"); // PK Name
var newsPKNameDic = db.GetTableKeyColumns<NewsInfo>(); // key=DbColumnName, Value= C# Property Info
Console.Write("newsPKName: ");
PrintStringPropertyInfoDic(newsPKNameDic); // ( NewsInfoId: NewsInfoId ) var newsTypePKNameDic = db.GetTableKeyColumns<NewsType>(); // key=DbColumnName, Value= C# Property Info
Console.Write("newsTypePKName: ");
PrintStringPropertyInfoDic(newsTypePKNameDic); // (NewsTypeId: TypeId ) Console.WriteLine("\n"); // all column name - property info
var newsAllColumnNamePropInfoDic = db.GetTableColumns<NewsInfo>(); // key=DbColumnName, Value = C# Property Info
Console.Write("news all column name - property info dictionary: ");
PrintStringPropertyInfoDic(newsAllColumnNamePropInfoDic); //( NewsInfoId: NewsInfoId ),( Title: NewsInfoTitle ),( NewsTypeId: NewsTypeId ) var newsTypeAllColumnNamePropInfoDic = db.GetTableColumns<NewsType>(); // key=DbColumnName, Value = C# Property Info
Console.Write("news type all column name - property info dictionary: ");
PrintStringPropertyInfoDic(newsTypeAllColumnNamePropInfoDic); //( NewsTypeId: TypeId ),( NewsTypeName: TypeName ) Console.WriteLine("\n"); // all column name - property name
var newsAllColumnNamePropNameDic = db.GetPropertyColumnNames<NewsInfo>(); // key= C# Property Name, Value= DbColumnName
Console.Write("news all column name - property name dictionary: ");
PrintPkNameDicCore(newsAllColumnNamePropNameDic, null); // ( NewsInfoId: NewsInfoId ),( NewsInfoTitle: Title ),( NewsTypeId: NewsTypeId ) var newsTypeAllColumnNamePropNameDic = db.GetPropertyColumnNames<NewsType>(); // key= C# Property Name, Value= DbColumnName
Console.Write("news type all column name - property name dictionary: ");
PrintPkNameDicCore(newsTypeAllColumnNamePropNameDic, null); // ( TypeId: NewsTypeId ),( TypeName: NewsTypeName ) Console.WriteLine("\n"); //经过测试,下面这 3 行代码发生了异常!
//List<EntityKey> newDependentList = db.GetDependentTypes(typeof(NewsInfo));
//Console.WriteLine("news dependent types: ");
//PrintEntityKeyList(newDependentList);
//Console.WriteLine(""); List<EntityKey> newsTypeDependentList = db.GetDependentTypes(typeof(NewsType));
// newsTypeDependentList 里面的信息如下:
// type= C#实体类的名称,比如:NewsInfo。
// Keys = 一个或外键字段对应的 C# Property 信息。比如:Nullable<int> NewsTypeId
Console.WriteLine("news type dependent types: ");
PrintEntityKeyList(newsTypeDependentList); // ( NewsInfo: { type=Nullable`1, name=NewsTypeId } ) Console.WriteLine("\n"); //
var newsPKColumnIdentityDic = db.GetComputedColumnNames<NewsInfo>();
Console.Write("news primaryKey column name - identity dictionary: ");
PrintPkNameDicCore(newsPKColumnIdentityDic, null); // ( NewsInfoId: True ) var newsTypePKColumnIdentityDic = db.GetComputedColumnNames<NewsType>();
Console.Write("news type primaryKey column name - identity dictionary: ");
PrintPkNameDicCore(newsTypePKColumnIdentityDic, null); // ( NewsTypeId: True ) Console.WriteLine("\n"); //
string newsInfoTitleColumnName = db.GetColumnName<NewsInfo>("NewsInfoTitle");
Console.Write("newsInfo title column name: " + newsInfoTitleColumnName); // Title
Console.WriteLine(""); string typeNameColumnName = db.GetColumnName<NewsType>("TypeName");
Console.Write("NewsType typeName column name: " + typeNameColumnName); // NewsTypeName
Console.WriteLine(""); Console.WriteLine("\n"); } static void PrintStringPropertyInfoDic(Dictionary<string, PropertyInfo> infoDic)
{
PrintPkNameDicCore<PropertyInfo>(infoDic, t => t.Name);
} static void PrintPkNameDicCore<T>(Dictionary<string, T> infoDic, Func<T, object> printCoreFunc)
{
int i = ;
foreach (var item in infoDic)
{
if (i > )
{
Console.Write(",");
}
Console.Write("( {0}: {1} )", item.Key, printCoreFunc == null ? item.Value : printCoreFunc(item.Value));
i++;
}
Console.WriteLine("");
} static void PrintEntityKeyList(IEnumerable<EntityKey> entityKeyList)
{
int i = ;
foreach (var item in entityKeyList)
{
if (i > )
{
Console.Write(",");
}
string keyTextInfo = string.Join(",", item.Keys.Select(c => string.Format("type={0}, name={1} ", c.PropertyType.Name, c.Name)));
Console.Write("( {0}: {{ {1} }} )", item.Type.Name, keyTextInfo);
i++;
}
Console.WriteLine("");
}
} }
运行效果图

谢谢浏览!
Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(五)的更多相关文章
- Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(一)
1. 案例1 - 类型和表之间的EF代码优先映射 从EF6.1开始,有一种更简单的方法可以做到这一点.有关 详细信息,请参阅我的新EF6.1类型和表格之间的映射. 直接贴代码了 从EF6.1开始,有一 ...
- Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(四)
经过上一篇,里面有测试代码,循环60万次,耗时14秒.本次我们增加缓存来优化它. DbContextExtensions.cs using System; using System.Collectio ...
- Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(三)
接着上一篇,我们继续来优化. 直接贴代码了: LambdaHelper.cs using System; using System.Collections.Generic; using System. ...
- Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(二)
接着上一篇 直接贴代码了: using System; using System.Collections.Generic; using System.Data.Entity; using System ...
- 浅析Entity Framework Core中的并发处理
前言 Entity Framework Core 2.0更新也已经有一段时间了,园子里也有不少的文章.. 本文主要是浅析一下Entity Framework Core的并发处理方式. 1.常见的并发处 ...
- 在Entity Framework 7中进行数据迁移
(此文章同时发表在本人微信公众号“dotNET每日精华文章”,欢迎右边二维码来关注.) 题记:虽然EF7重新设计了Entity Framework,不过也还是能够支持数据迁移的. Entity Fra ...
- [Programming Entity Framework] 第3章 查询实体数据模型(EDM)(一)
http://www.cnblogs.com/sansi/archive/2012/10/18/2729337.html Programming Entity Framework 第二版翻译索引 你可 ...
- 如何处理Entity Framework / Entity Framework Core中的DbUpdateConcurrencyException异常(转载)
1. Concurrency的作用 场景有个修改用户的页面功能,我们有一条数据User, ID是1的这个User的年龄是20, 性别是female(数据库中的原始数据)正确的该User的年龄是25, ...
- Entity Framework添加记录时获取自增ID值
与Entity Framework相伴的日子痛并快乐着.今天和大家分享一下一个快乐,两个痛苦. 先说快乐的吧.Entity Framework在将数据插入数据库时,如果主键字段是自增标识列,会将该自增 ...
随机推荐
- Installation request for topthink/think-captcha ^3.0 -> satisfiable by topthink/think-captcha[v3.0.0].
ThinkPHP5.1安装图形验证码的时候报错: Problem 1 - Installation request for topthink/think-captcha ^3.0 -> sati ...
- C# 局部类/方法
没怎么用过的东西. 算是比较神奇的东西(见识短[笑]). 关键字是partial 如果在类应用关键字,则是局部类. 如果在方法应用关键字,则是局部方法. 局部类理解差不多就是一个东西分开了,但是还是一 ...
- oracle中decode函数用法及应用
用法 1.decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值) 相当于if else 那种方式. 2.decode(字段或字段的运算,值1,值2,值3) 当字段或字段的运 ...
- 2018-2-13-win10-uwp-切换主题
原文:2018-2-13-win10-uwp-切换主题 title author date CreateTime categories win10 uwp 切换主题 lindexi 2018-2-13 ...
- qt 界面去掉系统边框
该代码在Qt5框架编辑,使用该类时, 直接继承这个类就可以了. 实现了拖拽功能和关闭功能,如果需要放大缩小功能, 需自己实现. 1 #ifndef CUSTOMIZE_QWIDGET_H #defin ...
- 5-API 网关 kong 实战
原文:https://cloud.tencent.com/developer/article/1477672 1. 什么是Kong? 目前互联网后台架构一般是采用微服务,或者类似微服务的形式,应用的请 ...
- python数据挖掘之数据探索第一篇
目录 数据质量分析 当我们得到数据后,接下来就是要考虑样本数据集的数据和质量是否满足建模的要求?是否出现不想要的数据?能不能直接看出一些规律或趋势?每个因素之间的关系是什么? 通过检验数据集的 ...
- PHP面试题2019年奇虎360面试题及答案解析
一.单选题(共29题,每题5分) 1.以下代码 a.php 输出的结果是? a.php 的代码如下: b.php的代码如下: A.foo in a B.什么也不输出 C.报错 D.foo in b 参 ...
- python使用face_recognition包的环境设置
在使用face_recognition包进行人脸识别时,环境是非常重要的,但是网上办法特别纷杂,今天介绍一种特别简单的办法,希望能帮助到大家,少走些坑. 1.首先应该下载dlib安装包(例如:dlib ...
- python的pip安装时,使用国内Pypi源
有时,国外的网速确实不理想. 想安装python库,还是国内快点. 参考URL: http://www.mamicode.com/info-detail-2248964.html 阿里云 http:/ ...