I am trying to write to the database using projection to avoid having to map a domain object to one that matches the table layout. Every projection example that I find however only shows how to read from the database. How do I project my entity to its database version to insert it?
class Foo
{
//...
}
class FooEF
{
//...
}
DbSet<FooEF> dbSet;
// Read
var foos = dbSet.Select(fooEF => new Foo { ... }).ToList();
// Write
???
CodePudding user response:
You cannot do that with EF Core. Any Insert/Update/Delete should go via change tracker.
Anyway there is extension linq2db.EntityFrameworkCore which can help in such query (disclaimer: I'm one of the creators)
var foos = dbSet.Select(fooEF => new Foo { ... });
foos.Insert(dbSetFoo.ToLinqToDBTable(), x => x);
Extension will create INSERT FROM
SQL and no data will be transferred to the client.
CodePudding user response:
You need to use your db context. And you have to define dbSet for Foo
type
public class ApplicationDbContext : DbContext
{
public DbSet<Foo> DbSetFoo{ get; set; }
public DbSet<FooEF> DbSetFooEF { get; set; }
...
}
...
var foos = dbSet.Select(fooEF => new Foo {...}).ToList().ForEach(foo=>context.DbSetFoo.Add(fooEf));
context.SaveChanges();