简体   繁体   English

C#EF从另一个表中查找数据的最佳方法

[英]C# EF best way to lookup data from one table within another

I met situation I have to write app where I'm taking bunch of records from tableA then for each of record I have to do lookup against tableB to pull extra information (get another 3 columns). 我遇到了这样的情况,我必须编写应用程序,在该应用程序中我要从tableA获取一堆记录,然后对于每个记录我都必须针对tableB进行查找以获取更多信息(获取另外3列)。

TableA is a small table (<1000 records), but tableB is much bigger. TableA是一个小表(<1000个记录),但是tableB大得多。 Also, these resides in separate DB on the same DB server. 而且,它们驻留在同一数据库服务器上的单独数据库中。

What would be best approach to get it optimized? 什么是使其最佳化的最佳方法?

There is no option to get all records into list of objects from tableB then operate on it, rather I would need to run LINQ query for each of tableA element(object) against tableB . 没有选择将所有记录从tableB获取到对象列表中然后对其进行操作的选项,而是我需要针对tableB对每个tableA element(object)运行LINQ查询。 This is part of my MVC so could you please provide me an draft of solution, described at high level, rather than providing code. 这是我的MVC的一部分,因此,您能否提供给我有关解决方案的草稿(从高层次进行描述),而不是提供代码。

EDIT The tableA records need to be "enriched" all against tableB before they are displayed, in effecitve this may be +/- 500 tableA records to be lookup against tableB. 编辑在显示tableA记录之前,需要针对tableB全部“丰富”它们,实际上这可能是要对tableB进行查找的+/- 500个tableA记录。 Also, limitation is I have only read access to the tableB..no option to write procedures, etc 另外,限制是我只能对tableB进行读取访问。没有写程序等的选项

You could create a view in one of the databases that combines data in table A and B. Then map your entity to that view. 您可以在一个数据库中创建一个视图,该视图结合了表A和B中的数据。然后将您的实体映射到该视图。 Check this out https://www.mssqltips.com/sqlservertip/1990/how-to-use-sql-server-views-with-the-entity-framework/ 检查一下https://www.mssqltips.com/sqlservertip/1990/how-to-use-sql-server-views-with-the-entity-framework/

Without seeing your models and query, it is hard to provide an accurate answer. 如果不查看模型和查询,很难提供准确的答案。 However, the best start is within the database (I would assume SQL Server 2012+). 但是,最好的开始是在数据库内(我假设是SQL Server 2012+)。

From your description, the generated query should look, in a very simplified way, like the following: 根据您的描述,生成的查询应以非常简化的方式看起来像以下内容:

SELECT A.*, B.Col1, B.Col2, B.Col3
FROM Db1.dbo.TableA AS A
   JOIN Db2.dbo.TableB AS B ON B.Id = A.FkToBId

According to this question and its accepted answer, there is no big difference between selecting from the same database vs. selecting from another database within the same instance . 根据这个问题及其公认的答案,从同一数据库中选择与在同一实例中从另一数据库中选择之间没有太大区别。

If TableB is big, you should avoid table scans, so the following index should be a good start: 如果TableB大,则应避免进行表扫描,因此以下索引应该是一个好的开始:

CREATE INDEX IDX_TableB_Id ON TableB (Id) INCLUDE (Col1, Col2, Col3)

However, if the schema is properly normalized, the lookup key should also be a primary key and this index should not be required. 但是,如果对模式进行了适当的规范化,则查找关键字也应该是主关键字,并且不需要该索引。 I think that if it is clustered, it might bring extra benefit. 我认为,如果将其群集,则可能会带来额外的好处。

Of course, there is a chance that your LINQ generates a slightly different query. 当然,您的LINQ有可能生成稍微不同的查询。 If this is the case, edit your question and include table schema, LINQ and generated query. 在这种情况下,请编辑您的问题并包括表架构,LINQ和生成的查询。

[EDIT] [编辑]

Using SqlQuery is an option, but I am thinking about another way: 使用SqlQuery是一个选项,但是我在考虑另一种方法:

1) Generate a database context for each database. 1)为每个数据库生成一个数据库上下文。 Lets call them DbContextA and DbContextB 我们称它们为DbContextADbContextB

2) Get only required information from TableB , store it in a dictionary for fast lookups and use in an aggregated query. 2)仅从TableB获取必需的信息,将其存储在字典中以进行快速查找,并在聚合查询中使用。

var ids = DbContextA.TableA.AsNoTracking().Select(item => item.FkToBId).ToList();
var bInfo = DbContextB.TableB.AsNoTracking()
   .Where(item => ids.Contains(item.id)) 
   .ToDictionary(
         item => item.Id, 
         item => new { item.Col1, item.Col2, item.Col3 }
   );

var aggrInfo = DbContextA.TableA.AsNoTracking()
   .ToList()
   .Select(item => new 
       { 
            AField = item, 
            Col1 = bInfo[item.FkToBId],
            Col2 = bInfo[item.FkToBId],
            Col3 = bInfo[item.FkToBId]
       };

If this does not provide the required efficiently, SqlQuery remains the only option, as a database context cannot work with two databases at once ( source ). 如果这不能有效地提供所需的资源,则SqlQuery仍然是唯一的选择,因为一个数据库上下文不能一次与两个数据库一起工作( )。

You should create a one class means .cs file and add all the columns of TableA and TableB which is required. 您应该创建一个类均值.cs文件,并添加所需的TableA和TableB的所有列。

Let see and Example Here i am having two tables category and sub category i want the name of the category and want to show the list. 让我们看一下示例。在这里,我有两个表类别和子类别,我想要类别的名称并想要显示列表。

public class SubCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Image { get; set; }
    public Nullable<bool> Isdisplay_ { get; set; }
    public Nullable<int> CatId { get; set; }
    public string CatName { get; set; }

}

var data = (from t in db.SubCategories
join ts in db.Categories on t.CatId equals ts.CategoryId 
select new { a1 = t.SubId, a2 = t.SubImage, a3 = t.SubIsdisplay_, a4 = 
 t.SubName, a5 = ts.CategoryName }).ToList();

        List<SubCategory> p1 = new List<SubCategory();
        foreach (var i in data)
        {
            SubCategory p2 = new SubCategory();
            p2.Id = i.a1;
            p2.Name = i.a4;
            p2.Image = i.a2;
            p2.Isdisplay_ = i.a3;
            p2.CatName = i.a5;

            p1.Add(p2);
        }
        return p1;

Now you can use the list p1 to show your data. 现在,您可以使用列表p1来显示数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 c# 中表示此查找表的最佳方式 - best way to represent this lookup table in c# 将一行“数据”从一个C#控制台应用程序传递到另一个C#控制台应用程序的最佳方法是什么? - What's the best way to pass a “row of data” from one C# console app to another C# console app? C#EF如果表中存在行,则选择它,否则从另一表中选择 - C# EF if row exists in table one select it else select from another table 在表中查找值并用数据填充的正确方法 - The right way to lookup a value from within a table and fill it with data 在C#中将Blob数据从一个表复制到另一个表 - copy blob data from one table to another in c# 如何将数据从一个表移动到另一个C# - how to Move data from one table to another c# C#将表格单元数据从一页发送到另一页 - C# send table cell data from one page to another 将查找表从数据库加载到 C# 程序 - 数据结构? - Loading a lookup table from a database into a C# program - data structure? 将文件从一个网络移动到另一个网络的最佳方式 c# iis - Best way of moving a file from one network to another c# iis 使用C#将变量/参数从一类提供给另一类的最佳方法是什么 - What is the best way to give variable/argument from one class to another using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM