Home > Software engineering >  Inserting Bunch Data - Entity Framework C#
Inserting Bunch Data - Entity Framework C#

Time:11-23

Here is my query in SQL language:

INSERT INTO db.server(client_id, server_id, count) 
    SELECT id, type, COUNT(*) 
    FROM db.service 
    GROUP BY id, type

How to convert such an insert to a LINQ (for Entity Framework) query?

CodePudding user response:

The following query is equivalent to your query in SQL.

var list = db.Services
           .GroupBy(a => new { a.ID, a.Type })
           .Select(a => new Server { Client_ID = a.Key.ID, Server_ID = a.Key.Type, Count = a.Select(b => b.ID).Count() }).ToList();


//add to db
db.Servers.AddRange(list);
db.SaveChanges();
  • Related