简体   繁体   English

如何在非关系表上使用实体框架执行批量上传

[英]How to perform bulk upload using entity framework on non relational tables

I am having 3 tables 我有3张桌子

CREATE TABLE [dbo].[TableA](
[TableAID] [bigint] IDENTITY(1,1) NOT NULL,
[PipelineId] [char](10) NULL,
[PipelinePointId] [char](20) NULL,
[Formula] [varchar](500) NULL,
[PipelinePriority] [smallint] NULL

CREATE TABLE [dbo].[TableB](
[TableBID] [smallint] IDENTITY(1,1) NOT NULL,
[UtilityId] [varchar](10) NULL,
[PoolId] [varchar](20) NULL,
[CustomerId] [int] NULL,
[AssetId] [smallint] NULL,
[StartDate] [datetime] NULL,
[EndDate] [datetime] NULL


CREATE TABLE [dbo].[JuntionTable](
[JunctionTableID] [bigint] IDENTITY(1,1) NOT NULL,
[TableAID] [bigint] NOT NULL,
[ParentID] [smallint] NOT NULL, --(ParentID is TableBID)
[AssetType] [nchar](10) NULL,

How can we insert data in this table through entity frame work? 我们如何通过实体框架在该表中插入数据? we are using Fluent API 我们正在使用Fluent API

Insertion sequence is 插入顺序为

  1. Insert into TalbeA 插入TalbeA
  2. Insert into TableB 插入表B
  3. Insert into JunctionTable with JuntionTable.TableAID as TalbeAID and JunctionTable.ParentID as TableBID 使用JuntionTable.TableAID作为TalbeAID和JunctionTable.ParentID作为TableBID插入JunctionTable

We cannot have foreign key relation in JunctionTable, since junction table will be holding data from different tables. 我们不能在JunctionTable中具有外键关系,因为联结表将保存来自不同表的数据。

You can use SQLBulkCopy to do this, something along the lines of this: 您可以使用SQLBulkCopy来执行此操作,类似于以下内容:

using (var bulkCopy = new SqlBulkCopy(_DbContext.Database.Connection.ConnectionString, SqlBulkCopyOptions.TableLock))
        {
            bulkCopy.BulkCopyTimeout = 1200; // 20 minutes
            //bulkCopy.BatchSize = listTableColumns.Count();
            bulkCopy.BatchSize = 10000;
            bulkCopy.DestinationTableName = "TableA";

            var table = new DataTable();
            var props = TypeDescriptor.GetProperties(typeof(TableA))                                     
                //Dirty hack to make sure we only have system data types                                      
                //i.e. filter out the relationships/collections
                .Cast<PropertyDescriptor>()
                .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
                .ToArray();
            foreach (var propertyInfo in props) 
            { 
                bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name); 
                table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType); 
            }
            // Add Database ID
            bulkCopy.ColumnMappings.Add("TableAID", "TableAID");
            table.Columns.Add("TableAID", typeof(int));

            var values = new object[props.Length + 1];
            foreach (var item in MyRowsToInsert) 
            { 
                for (var i = 0; i < values.Length - 1; i++) 
                { 
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }

            bulkCopy.WriteToServer(table);
        }

Please try the below ,A many-to-many relationship is defined in code by the inclusion of collection properties in each of the entities 请尝试以下操作,通过在每个实体中包含集合属性,在代码中定义了多对多关系

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
    public ICollection<BookCategory> BookCategories { get; set; }
} 

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public ICollection<BookCategory> BookCategories { get; set; }
}

public class BookCategory
{
    public int BookId { get; set; }
    public Book Book { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

--you have to configured relationship via the Fluent API for EF Core 1.1.0 to be able to map it successfully as following -您必须通过Fluent API for EF Core 1.1.0配置关系才能成功映射它,如下所示

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<BookCategory>()
        .HasKey(bc => new { bc.BookId, bc.CategoryId });

    modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Book)
        .WithMany(b => b.BookCategories)
        .HasForeignKey(bc => bc.BookId);

    modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Category)
        .WithMany(c => c.BookCategories)
        .HasForeignKey(bc => bc.CategoryId);
}

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

相关问题 如何使用实体框架对与外键相关的多个表执行批量插入 - How to perform bulk insert into multilple tables which are related with foreign keys using entity framework 实体框架继承关系表 - Entity Framework Inheritance relational tables 实体框架中的关系表存在问题 - Issue with relational tables in Entity Framework 使用实体框架从具有条件的关系表中查询 c# - Query from relational tables with conditions using Entity Framework c# 如何避免使用Entity Framework在关系引用循环中检索关系对象? - How to avoid retrieving relational objects within relational reference loop using Entity Framework? 实体框架核心:LINQ 建议使用包含关系表的更好方法 - Entity Framework Core : LINQ advise needed on better approach using include for relational tables 使用实体框架C#WebApi从关系表中获取数据 - Get data from relational tables using entity framework C# WebApi 如何使用对象上下文在实体框架中使用批量插入? - How to use Bulk Insert in Entity Framework using Object Context? 如何在Entity Framework 5中执行回滚? - How to perform rollback in Entity Framework 5? 使用实体框架更新批量插入替代方案? - Updated bulk insertion alternative using Entity Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM