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在将数据插入数据库时,如果主键字段是自增标识列,会将该自增 ...
随机推荐
- oracle 关联更新
不多说了,我们来做实验吧. 创建如下表数据 select * from t1 ; select * from t2; 现需求:参照T2表,修改T1表,修改条件为两表的fname列内容一致. 方式1,u ...
- 手写SpringMVC实现过程
1. Spring Boot,Spring MVC的底层实现都是Servlet的调用. 2. Servlet的生命周期里面首先是类的初始化,然后是类的方法的调用,再次是类的销毁. 3. 创建一个spr ...
- 安装Keepalived namespaces.c:187: error: ‘SYS_setns’ undeclared (first use in this function)
错误信息 namespaces.c: In function ‘setns’: namespaces.c:: error: ‘SYS_setns’ undeclared (first use in t ...
- .NET MVC5简介(四)Filter和AuthorizeAttribute权限验证
在webform中,验证的流程大致如下图: 在AOP中: 在Filter中: AuthorizeAttribute权限验证 登录后有权限控制,有的页面是需要用户登录才能访问的,需要在访问页面增加一个验 ...
- 读Xamarin文档记录
//怎样判断Wifi是否连接if (Connectivity.NetworkAccess == NetworkAccess.None) { ... } 连接改变的事件,判断事件改变后是否还处于连接状态 ...
- 由 ToString()和Convert.ToString() 引发的问题
对于久经沙场的程序猿来说,类型转换再熟悉不过了,在代码中我们也会经常用到. 前几天,有个学生问我关于类型转换ToString()和Convert.ToString()的区别,这么常用的东西我竟然支支吾 ...
- form分辨率
近期做项目时,遇到开发的winform在自己电脑上可以正常显示,共享到其他电脑就事儿不能显示了: [转载自:http://blog.csdn.net/lcawen88/article/details/ ...
- Android多module下重复jar包问题
版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/166 Android多module下重复jar包问题 An ...
- git在idea中的冲突解决(非常重要)
1.什么是冲突 冲突是指当你在提交或者更新代码时被合并的文件与当前文件不一致.读起来有点绕,结合下面的案例理解. 从上面对冲突的定义来看,冲突时发生在同一个文件上的. 2.生产上冲突的场景 常见冲突的 ...
- Python—路由追踪(并生成追踪图片)
需要先安装两个包 [root@localhost ~]# yum install graphviz // 为了使用dot命令 [root@localhost ~]# yum install Image ...