0

我想知道在以下情况下推荐什么:

我有一个大循环,我遍历该循环以获取一个 ID,然后将其存储在数据库中,如下所示:

foreach (var rate in rates)
{
    // get ID from rate name
    Guid Id = dbContext.DifferentEntity
        .Where(x => x.Name == rate.Name).FirstOrDefault();

    // create new object with the newly discovered 
    // ID to insert into the database
    dbContext.YetAnotherEntity.Add(new YetAnotherEntity
    {
        Id = Guid.NewGuid(),
        DiffId = Id,
    }
}

这样做会更好/更快吗(首先获取所有DifferentEntityID,而不是单独查询它们)?

List<DifferentEntity> differentEntities = dbContext.DifferentEntity;

foreach (var rate in rates)
{
    // get ID from rate name
    Guid Id = differentEntities
        .Where(x => x.Name == rate.Name).FirstOrDefault();

    // create new object with the newly discovered 
    // ID to insert into the database
    dbContext.YetAnotherEntity.Add(new YetAnotherEntity
    {
        Id = Guid.NewGuid(),
        DiffId = Id,
    }
}

差异是微不足道的还是我应该考虑的?谢谢你的建议。

4

3 回答 3

2

将您的费率名称存储在排序的字符串数组 ( string[]) 中,而不是 aListCollection。然后使用Array.BinarySearch()使您的搜索更快。我要写的其余内容已经由上面的@Felipe 写了。

于 2013-08-15T14:59:39.117 回答
1

跑他们的马!真的有很多我们不知道的。是否可以将所有实体保存在内存中?其中有多少是重复的Name

一个简单的解决方案,从数据库中获取一次并使用并行性:

// Fetch entities
var entitiesDict = dbContext.DifferentEntity
     .Distinct(EqualityComparerForNameProperty).ToDictionary(e => e.Name); 

// Create the new ones real quick and divide into groups of 500 
// (cause that horse wins in my environment with complex entities, 
// maybe 5 000 or 50 000 fits your scenario better since they are not that complex?)
var newEnts = rates.AsParallel().Select((rate, index) => {
  new {
        Value = new YetAnotherEntity
           { Id = Guid.NewGuid(), DiffId = entitiesDict[rate.Name],},
        Index = index
     }
  })
.GroupAdjacent(anon => anon.Index / 500) // integer division, and note GroupAdjacent! (not GroupBy)
.Select(group => group.Select(anon => anon.Value)); // do the select so we get the ienumerables

// Now we have to add them to the database
Parallel.ForEach(groupedEnts, ents => {
   using (var db = new DBCONTEXT()) // your dbcontext
   {
     foreach(var ent in ents)       
       db.YetAnotherEntity.Add(ent);

     db.SaveChanges();
   }
});

一般来说,在数据库场景中,昂贵的东西是获取和提交,所以尽量将它们保持在最低限度。

于 2013-08-16T10:07:46.623 回答
0

您可以减少在数据库中执行的查询数量。例如,获取所有名称并查询名称包含的 findind Id。

尝试这样的事情。

// get all names you have in rates list...
var rateNames = rates.Select(x => x.Name).ToList();

// query all Ids you need where contains on the namesList... 1 query, 1 column (Id, I imagine)
var Ids = dbContext.DifferentEntity.Where(x => rateNames.Contains(x.Name).Select(x => x.Id).ToList();

// loop in Ids result, and add one by one
foreach(var id in Ids)
    dbContext.YetAnotherEntity.Add(new YetAnotherEntity
    {
        Id = Guid.NewGuid(),
        DiffId = id,
    }
于 2013-08-15T14:56:25.560 回答