EntityFramework AddRange不会插入

时间:2016-03-27 18:19:35

标签: c# entity-framework

我正在尝试使用以下代码测试addRange性能:

    [TestMethod, TestCategory("Unit EfPerformanceTests")]
    public async Task EfPerformanceGlobal_AddRangeInsertFor10000Rows_SaveToDatabase()
    {
        var rowAmountPre = await _unit.Repository<PaymentProvider>().Queryable().ToListAsync();
        var rowAmountToInsert = 10000;

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        var paymentProviders = new List<PaymentProvider>();

        for (int i = 0; i < rowAmountToInsert; ++i)
        {
            var paymentProvider = new PaymentProvider
            {
                Label = "Provider Name"
            };

            paymentProviders.Add(paymentProvider);
        }


        _unit.Repository<PaymentProvider>().InsertGraphRange(paymentProviders);
        await _unit.SaveChangesAsync();

        stopwatch.Stop();

        var filePath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + @"\EfPerformanceTests.txt";
        File.WriteAllText(filePath, "AddRangeInsert(rows " + rowAmountToInsert + "): " + stopwatch.Elapsed);

        var rowAmountPost = await _unit.Repository<PaymentProvider>().Queryable().ToListAsync();

        Assert.AreEqual(rowAmountPre.Count + rowAmountToInsert, rowAmountPost.Count);
    }

数据库抛出异常:

  

System.InvalidOperationException:保存或接受更改失败   因为不止一个类型的实体   &#39; App.Model.Context.PaymentProvider&#39;具有相同的主键值。   确保显式设置的主键值是唯一的。确保这件事   数据库生成的主键在中正确配置   数据库和实体框架模型。使用实体设计器   用于Database First / Model First配置。使用   &#39; HasDatabaseGeneratedOption&#34;流利的API或   &#39; DatabaseGeneratedAttribute&#39;用于Code First配置。

在db表中设置自动增量时,我不确定为什么EF会识别实体的相同主键值。

编辑PaymentProvider实体:

using System;
using System.Collections.Generic;
using Repository.Pattern.Ef6;
using LocationApp.Model.Context;

public partial class PaymentProvider : Entity, IPaymentProvider
{
    public PaymentProvider()
    {
        this.LogPayments = new HashSet<LogPayment>();
    }

    public int Id { get; set; }
    public string Label { get; set; }

    public virtual ICollection<LogPayment> LogPayments { get; set; }
}

0 个答案:

没有答案