获取数据库表名从实体框架元数据 [英] Get Database Table Name from Entity Framework MetaData

查看:318
本文介绍了获取数据库表名从实体框架元数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一种方式来获得基础SQL表的名称为给定的实体类型。我已经试验周围的MetadataWorkspace查询,虽然我可以得到很多的对象或存储空间的信息,我似乎无法弄清楚如何在两者之间进行映射。

I'm trying to figure out a way to get the underlying SQL table name for a given entity type. I've experimented around with the MetadataWorkspace queries and while I can get lots of information from the object or the storage space, I can't seem to figure out how to map between the two.

所以说,我有一个类型的对象模型叫做查询 - ?在数据库中如何找到的表名(wws_lookups)

So say I have a type in the object model called Lookup - how do I find the tablename (wws_lookups) in the database?

我可以查询所有CSpace和SSpace的的EntityType对象,我可以看到正确的既列出,但我无法弄清楚如何从CSpace获得SSpace。

I can query all the EntityType objects for CSpace and SSpace and I can see both listed correctly but I can't figure out how to get SSpace from CSpace.

有没有办法做到这一点?

Is there any way to do this?

推荐答案

我知道这个职位是很老,但我会在这里把我的解决方案,它可能是有用的人。我使用的是薛明的方式(提取表名 .ToTraceString()),但有一些修改,因为他的code不会工作,如果该表是不是在SQL Server的默认模式( DBO。{表名} )。

I know this post is quite old, but I'll put here my solution, it may be useful for someone. I'm using Nigel's approach (extracting table name from .ToTraceString()) but with some modifications, because his code won't work if the table is not in the default SQL Server schema (dbo.{table-name}).

我创建的扩展方法的DbContext 的ObjectContext 目标:

I've created extension methods for DbContext and ObjectContext objects:

public static class ContextExtensions
{
    public static string GetTableName<T>(this DbContext context) where T : class
    {
        ObjectContext objectContext = ((IObjectContextAdapter) context).ObjectContext;

        return objectContext.GetTableName<T>();
    }

    public static string GetTableName<T>(this ObjectContext context) where T : class
    {
        string sql = context.CreateObjectSet<T>().ToTraceString();
        Regex regex = new Regex("FROM\s+(?<table>.+)\s+AS");
        Match match = regex.Match(sql);

        string table = match.Groups["table"].Value;
        return table;
    }
}

更多细节在这里:
实体框架:获取映射表的名字从实体

More details here:
Entity Framework: Get mapped table name from an entity

这篇关于获取数据库表名从实体框架元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆