Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(二)
2024-08-26 19:54:19
接着上一篇
直接贴代码了:
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");
}
}
}
运行截图:
谢谢浏览!
最新文章
- 宿主机ping不通虚拟机cenos7
- C++11:新式的字符串字面常量(String Literal)
- web移动端性能调优及16ms优化
- C语言 百炼成钢8
- spoj LCMSUM sigma(lcm(i,n));
- SrcollView分页加载数据(MainActivity)
- Git教程(1)官网及官方中文教程
- 计算任意位数的Pi
- [week2]每周总结与工作计划
- EasyUI DataGrid使用示例
- 认识 Linux 文件权限
- centos系统安装第三方源EPEL
- Images corrections preview with lensfun 不同型号镜头预览图 828张 合集
- vue 中跨组件的表单验证
- robot framework测试数据语法
- HDMI SCDC处理过程
- ScrollView match_parent不起作用
- ATM_购物车作业
- Mac 10.12安装Homebrew图形化界面管理工具Cakebrew
- 20145307第四次JAVA学习实验报告
热门文章
- Kafka常见错误整理(不断更新中)
- win7系统下安装Ubuntu18.04组成双系统
- MySQL EXPLAIN 语句
- Python3---爬虫---抓取百度贴吧
- linux下编译安装MariaDB 10.4.7,解决错误:cannot access ‘/auth_pam_tool_dir’: No such file or directory
- 记一次asp.net core 在iis上运行抛出502.5错误
- echarts水球图编写
- Linux下设置root密码
- Discuz! 全局变量说明
- 【CobaltStrike】对CobaltStrike内置功能模块的了解