Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(二)
接着上一篇
直接贴代码了:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using EntityFramework.Extensions; namespace EntityFrameworkSample
{
class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext(@"Data Source=.\SQLExpress;Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;Password=123456"))
{
string blogTableName = GetTableName(typeof(Blog), db);
string postTableName = GetTableName(typeof(Post), db); //Console.WriteLine("Blog maps to: {0}", blogTableName);
//Console.WriteLine("Post maps to: {0}", postTableName); string blogUrlColumnName = GetColumnName(typeof(Blog), "BlogUrl", db);
string postTitleColumnName = GetColumnName(typeof(Post), "PostTitle", db); Console.WriteLine("Blog.BlogUrl maps to: {0}.{1}", blogTableName, blogUrlColumnName);
Console.WriteLine("Post.PostTitle maps to: {0}.{1}", postTableName, postTitleColumnName);
}
Console.ReadLine();
} public static string GetTableName(Type type, DbContext context)
{
var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; // Get the part of the model that contains info about the actual CLR types
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); // Get the entity type from the model that maps to the CLR type
var entityType = metadata
.GetItems<EntityType>(DataSpace.OSpace)
.Single(e => objectItemCollection.GetClrType(e) == type); // Get the entity set that uses this entity type
var entitySet = metadata
.GetItems<EntityContainer>(DataSpace.CSpace)
.Single()
.EntitySets
.Single(s => s.ElementType.Name == entityType.Name); // Find the mapping between conceptual and storage model for this entity set
var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace)
.Single()
.EntitySetMappings
.Single(s => s.EntitySet == entitySet); // Find the storage entity set (table) that the entity is mapped
var table = mapping
.EntityTypeMappings.Single()
.Fragments.Single()
.StoreEntitySet; // Return the table name from the storage entity set
return (string)table.MetadataProperties["Table"].Value ?? table.Name;
} public static string GetColumnName(Type type, string propertyName, DbContext context)
{
var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; // Get the part of the model that contains info about the actual CLR types
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); // Get the entity type from the model that maps to the CLR type
var entityType = metadata
.GetItems< EntityType > (DataSpace.OSpace)
.Single(e => objectItemCollection.GetClrType(e) == type); // Get the entity set that uses this entity type
var entitySet = metadata
.GetItems < EntityContainer > (DataSpace.CSpace)
.Single()
.EntitySets
.Single(s => s.ElementType.Name == entityType.Name); // Find the mapping between conceptual and storage model for this entity set
var mapping = metadata.GetItems < EntityContainerMapping > (DataSpace.CSSpace)
.Single()
.EntitySetMappings
.Single(s => s.EntitySet == entitySet); // Find the storage entity set (table) that the entity is mapped
var tableEntitySet = mapping
.EntityTypeMappings.Single()
.Fragments.Single()
.StoreEntitySet; // Return the table name from the storage entity set
//var tableName = tableEntitySet.MetadataProperties["Table"].Value ?? tableEntitySet.Name; // Find the storage property (column) that the property is mapped
var columnName = mapping
.EntityTypeMappings.Single()
.Fragments.Single()
.PropertyMappings
.OfType < ScalarPropertyMapping > ()
.Single(m => m.Property.Name == propertyName)
.Column
.Name; //return tableName + "." + columnName;
return columnName;
}
} public class BloggingContext : DbContext
{
public BloggingContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{ } public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new BlogMap());
modelBuilder.Configurations.Add(new PostMap());
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
} public class Blog
{
public int BlogId { get; set; }
public string BlogUrl { get; set; } public List<Post> Posts { get; set; }
} public class Post
{
public int PostId { get; set; }
public string PostTitle { get; set; }
public string Body { get; set; } public int BlogId { get; set; }
public Blog Blog { get; set; }
} public class BlogMap : EntityTypeConfiguration<Blog>
{
public BlogMap()
{
this.HasKey(c => c.BlogId);
this.ToTable("t_blog");
this.Property(c => c.BlogUrl).HasColumnName("Url");
}
} public class PostMap : EntityTypeConfiguration<Post>
{
public PostMap()
{
this.HasKey(c => c.PostId);
this.ToTable("t_post");
this.Property(c => c.PostTitle).HasColumnName("Title");
}
}
}
运行截图:

谢谢浏览!
Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(二)的更多相关文章
- Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(一)
1. 案例1 - 类型和表之间的EF代码优先映射 从EF6.1开始,有一种更简单的方法可以做到这一点.有关 详细信息,请参阅我的新EF6.1类型和表格之间的映射. 直接贴代码了 从EF6.1开始,有一 ...
- Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(五)
直接贴代码了: NewsInfo 实体类: public class NewsInfo { public int NewsInfoId { get; set; } public string News ...
- 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. ...
- [Programming Entity Framework] 第3章 查询实体数据模型(EDM)(一)
http://www.cnblogs.com/sansi/archive/2012/10/18/2729337.html Programming Entity Framework 第二版翻译索引 你可 ...
- 浅析Entity Framework Core中的并发处理
前言 Entity Framework Core 2.0更新也已经有一段时间了,园子里也有不少的文章.. 本文主要是浅析一下Entity Framework Core的并发处理方式. 1.常见的并发处 ...
- 在Entity Framework 7中进行数据迁移
(此文章同时发表在本人微信公众号“dotNET每日精华文章”,欢迎右边二维码来关注.) 题记:虽然EF7重新设计了Entity Framework,不过也还是能够支持数据迁移的. Entity Fra ...
- 如何处理Entity Framework / Entity Framework Core中的DbUpdateConcurrencyException异常(转载)
1. Concurrency的作用 场景有个修改用户的页面功能,我们有一条数据User, ID是1的这个User的年龄是20, 性别是female(数据库中的原始数据)正确的该User的年龄是25, ...
- Entity Framework添加记录时获取自增ID值
与Entity Framework相伴的日子痛并快乐着.今天和大家分享一下一个快乐,两个痛苦. 先说快乐的吧.Entity Framework在将数据插入数据库时,如果主键字段是自增标识列,会将该自增 ...
随机推荐
- 利用zabbix监控ogg进程(Linux平台下)
前段时间生产的一个数据库的ogg进程挂了快半个月才被发现,已经起不来了,只有重新初始化再同步.因此很有必要监控下ogg的进程,这里给大家介绍如何使用zabbix监控oracle的ogg的进程.思路就是 ...
- Web前端—— JQuery迷你版实现以及使用
JQuery迷你版实现以及使用 tiny_jquery.js var $ = function (selector) { var ele = document.querySelector(select ...
- c# winform 窗体失去焦点关闭(钩子实现)
先来一个辅助类 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Inte ...
- 2019-6-5-WPF-拼音输入法
原文:2019-6-5-WPF-拼音输入法 title author date CreateTime categories WPF 拼音输入法 lindexi 2019-6-5 17:6:58 +08 ...
- JS原生对象实现异步请求以及JQ的ajax请求四种方式
一.JS原生方式异步请求 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="A ...
- FCC---Create a More Complex Shape Using CSS and HTML---一个粉色爱心
One of the most popular shapes in the world is the heart shape, and in this challenge you'll create ...
- js获取手机唯一标识码
Device模块管理设备信息,用于获取手机设备的相关信息,如IMEI.IMSI.型号.厂商等.通过plus.device获取设备信息管理对象. imei: 设备的国际移动设备身份码 imsi: 设备的 ...
- rocksdb和leveldb性能比较——写性能
前面学习了一下rocksdb,这个db是对leveldb的一个改进,是基于leveldb1.5的版本上的改进,而且leveldb1.5以后也在不断的优化,下面从写入性能对两者进行对比. 前言 比较的l ...
- Costco
1 会员制,并不是Costco成功的关键原因 Costco最早开始推行会员制的时候,其实遭遇了巨大的失败. 人们当时是不接受,也不理解会员制度的,没有多少人来办会员,Costco差点就死掉了. 那Co ...
- 渗透测试学习 十、 MSsql注入下
大纲:MySQL介绍及操作 MySQL注入原理 MySQL注入其他操作 一.MySQL介绍及操作 介绍 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle ...