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在将数据插入数据库时,如果主键字段是自增标识列,会将该自增 ...
随机推荐
- route 相关设置
Debian系统 查看路由表: root@debian:~# ip route default via 192.168.6.1 dev enp4s0 10.0.0.0/24 dev br0 proto ...
- MySql配置主从模式 Last_IO_Error: Fatal error: The slave I/O thread stops because master and slave have equal MySQL server UUIDs; these UUIDs must be different for replication to work.
今天在学习MyCat环境搭建的时候,在配置MySql的主从模式,发现slave在配置完毕后,配置的内容全部正确的情况下,报错了? Last_IO_Error: Fatal error: The sla ...
- C++ 手把手教你实现可变长的数组
01 实现自定义的可变长数组类型 假设我们要实现一个会自动扩展的数组,要实现什么函数呢?先从下面的main函数给出的实现,看看有什么函数是需要我们实现的. int main() { MyArray a ...
- Spring Boot的注解,你知道或者不知道的都在这里!
1.1 定义 Annotation(注解),用于为Java代码提供元数据.简单理解注解可以看做是一个个标签,用来标记代码.是一种应用于类.方法.参数.变量.构造器及包的一种特殊修饰符. 1.2 注解的 ...
- DS12C887实时时钟
实物图 引脚定义 GND. VCC:直流电源,其中VCC接+5V输入,GND接地,当VCC输入为+5V时,用户可以访问DS12C887内RAM中的数据,并可对其进行读.写操作:当VCC的输入小于+4. ...
- Android O的通知渠道适配
在 Android O 以后,Google引入了通知通道的概念,如果目标API大于 Android O ,不直指定通知渠道是不能发送通知的. 这里放一个我写好的通知方法,大家可以适当的改改再用,*当 ...
- split("\\,")引起的java.lang.ArrayIndexOutOfBoundsException异常解决方案
由split("\,")引起的指标越界异常 如果字符串最后分隔符里的字段为空,使用split("\\,")进行切割时,最后的空字段不会切割 例如"a, ...
- Mysql双主加Keepalived+读写分离
一.MySQL于keepalived简介** 前言: 在企业中,数据库高可用一直是企业的重中之重,中小企业很多都是使用mysql主从方案,一主多从,读写分离等,但是单主存在单点故障,从库切换成主库需要 ...
- CodeForces - 1251C (思维+贪心+归并排序)
题意 https://vjudge.net/problem/CodeForces-1251C 一个字符串,相邻的偶数奇数不能交换位置,其他相邻的情况可以交换,问字符串代表的数最小是多少. 思路 相邻的 ...
- 17.Java基础_初探类的private和public关键字
package pack1; public class Student { // 成员变量 private String name; private int age; // get/set方法 pub ...