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

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

问题描述

我试图找出一种方法来获取给定实体类型的基础 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.

所以说我在对象模型中有一个名为 Lookup 的类型 - 我如何在数据库中找到表名 (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?

推荐答案

我使用 Nigel 的方法(从 .ToTraceString() 中提取表名)但做了一些修改,因为他的代码不起作用如果表不在默认 SQL Server 架构中 (dbo.{table-name}).

I use 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}).

我为 DbContextObjectContext 对象创建了扩展方法:

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(@"FROMs+(?<table>.+)s+AS");
        Match match = regex.Match(sql);

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

此处有更多详细信息:
实体框架:获取来自实体的映射表名

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

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