简体   繁体   English

在实体框架C#中将表实体分配给具有相同架构的另一个表实体

[英]Assign Table Entity to another Table Entity with identical schemas in Entity Framework C#

I have two tables in my database with identical column names and column quantity. 我的数据库中有两个表,它们的列名和列数相同。 Table1 is a working table, where it is constantly being hit and iterated through. Table1是一个工作表,在其中不断对其进行击打和迭代。 Table2 is an exact replica of Table1 and is only used to archive Table1. Table2是Table1的精确副本,仅用于存档Table1。 Every week, a few rows in Table1 get copied into Table2 and removed from Table1. 每周,将Table1中的几行复制到Table2中并从Table1中删除。

Now that you have some context... 现在您有了一些上下文...

Table1 and Table2 are converted into Entities in EntityFramework. 表1和表2在EntityFramework中转换为实体。 I want to be able to either merge the two tables together in any fashion OR be able to assign each "item" to an identical "archiveItem" like the following: 我希望能够以任何方式将两个表合并在一起,或者能够将每个“项目”分配给相同的“ archiveItem”,如下所示:

var archiveObjects= new List<archiveObject>();
foreach(var object in objects)
{
    var objectConvertedToArchiveObject = (archiveObject) object;
    archiveObjects.Add(objectConvertedToArchiveObject);
}

There are 55 columns in each of these tables (entities). 每个表(实体)中有55列。 That is why I don't just assign each column (property). 这就是为什么我不只是分配每列(属性)的原因。

Thanks for your help in advance! 谢谢您的帮助!

There's no way in Entity Framework to "merge" two tables. 实体框架中无法“合并”两个表。 Each entity is intrinsically tied to one table. 每个实体本质上都与一个表相关联。 If you need to get all the data, from both tables you can either: 如果您需要从两个表中获取所有数据,则可以:

  1. Create a view at the database level and tie your entity to this view. 在数据库级别创建一个视图,并将您的实体绑定到该视图。 In the view, you will merge the data from the two distinct tables. 在视图中,您将合并两个不同表中的数据。 For your entity, you just need to decorate the class with [Table("YourViewName")] . 对于您的实体,您只需要用[Table("YourViewName")]装饰类。 However, views amongst other things are not indexed. 但是,其中的视图未编入索引。 It's fine if you intend to just pull all the data, but if you want to query into that data, the view is going to be a poor way to achieve that. 如果您只想提取所有数据,那很好,但是如果您要查询该数据,则视图将是实现该目标的一种糟糕方法。

  2. Have your two entities representing Table1 and Table2 both either inherit from a base class or implement an interface. 让您的两个代表Table1Table2实体都从基类继承或实现接口。 You can then create a list of that base class or interface, query the data from each table individually, and then combine them into the same list: 然后,您可以创建该基类或接口的列表,分别查询每个表中的数据,然后将它们组合到同一列表中:

     var combinedData = new List<ITable>(); combinedData.AddRange(db.Table1.ToList()); combinedData.AddRange(db.Table2.ToList()); 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM