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在将数据插入数据库时,如果主键字段是自增标识列,会将该自增 ...
随机推荐
- Docker - 快速入门(一)
概念 下面这三个概念一开始可能不好理解,等大家跟着博客把例子做完了,再回头来看应该就能理解了. docker image # docker镜像 镜像就是一个只读的模板.镜像可以用来创建Docker容 ...
- C#函数的参数传递2(ref\out)
using System; namespace class1 { class program { static void Main(string[] args) { Console.Write(&qu ...
- C#数组2(多维数组)
using System; namespace ConsoleApp3 { struct WuGong { public string Name; public int Attack; } class ...
- Wpf,Unity6
<?xml version="1.0" encoding="utf-8"?><packages> <package id=&quo ...
- Z从壹开始前后端分离【 .NET Core2.0/3.0 +Vue2.0 】框架之四 || Swagger的使用 3.2
本文梯子 本文3.0版本文章 前言 一.swagger的一般用法 0.设置swagger页面为首页——开发环境 1.设置默认直接首页访问 —— 生产环境 2.为接口添加注释 3.对 Model 也添加 ...
- h5本地存储登录页面实现记住密码功能
<!DOCTYPE html> <html> <head> <title></title> </head> <style ...
- js中for循环的研究
转自:http://blog.csdn.net/lushuaiyin/article/details/8541500 <html> <body> <b><ce ...
- Android 安全攻防(三): SEAndroid Zygote
转自:http://blog.csdn.net/yiyaaixuexi/article/details/8495695 在Android系统中,所有的应用程序进程,以及系统服务进程SystemServ ...
- 顺F速运国际版,你的密码漏点了
- 加密情况分析 对APP的分析过程,当然首先是安装,使用,抓包啦. 同样地,登录,抓包看看. 使用账号密码登录. - 壳呢? 虽然直接解密了顺F国际版的加密数据,但还是有必要看看它的APK. 经过分 ...
- sqlserver2008R2 本地不能用localhost连接
问题 在重新安装sql Server2008R2的时候,本地安装完成之后,想用localhost或者127.0.0.1登录的时候发现一直报错,无法连接,以下是解决方案. 打开Sql Server配置管 ...