Copying a table in Entity Framework - entity-framework

Using .NET Core 2.2 and Entity Framework what is the easiest way to copy a database table to a new database table.
i.e. creating an archive copy of that table.

I suggest using raw sql in EntityFrameworkCore to accomplish what you need.
dbContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
"INSERT INTO TABLE2
SELECT * FROM TABLE1" );

if memory is not an issue
var sourceFiles = _context.SourceTables.ToList();
foreach(var sourceFile in sourceFiles)
{
//if matching entity
_context.DestinationTables.Add(sourceFile);
//if not matching
var destination = new DestinationEntity
{
Prop1 = sourceFile.Prop1,
//other properties
}
_context.DestinationTables.Add(destination);
//if need to remove
_context.SourceTables.Remove(sourceFile);
}
_context.SaveChanges();

Related

Dynamic tables in Entity Framework

The table has to be created dynamically. The table name is dynamic (is sent to API) and columns are static.
Every time api is called, a new table is been created with different name.
Is it possible to do that in Entity Framework? If so - how?
DB is Posstgress.
Thanks
ADO is not the accepted way. I need to do it with Entity Framework.
I tried to write migration that will be activated just when API is called. But it seems that migration can run only when running first.
If you have a bunch of tables with the same columns and you want to switch between them at runtime, you can use SQL Queries.
var blogs = context.Blogs
.FromSql($"SELECT * FROM {QuoteName(tableName)}")
.ToList();
where QuoteName prevents SQL Injection attacks. This one is for SQL Server:
private static string QuoteName(string identifier)
{
var sb = new StringBuilder(identifier.Length + 3, 1024);
sb.Append('[');
foreach (var c in identifier)
{
if (c == ']')
sb.Append(']');
sb.Append(c);
}
sb.Append(']');
return sb.ToString();
}

Creating new entity framework record from related object

Is there a way to use SetValues() when creating an entity framework object.
I have a class with same field definitions as my entity framework class and found this explanation of an easier way to update ef records using the SetValues function.
https://researchaholic.com/2013/02/06/entity-framework-5-easier-way-to-update-record/
The question I have is this: Is there a similar way to create new ef records without specifying every field like this:
var newItm = new Import.EntityClasses.ImportSiteList {
SiteId = ssItm.SiteId,
OrganizationId = ssItm.OrganizationId,
TimeZoneId = ssItm.TimeZoneId
};
tbl.Add(newItm);
This is how you can do
var newItm = new Import.EntityClasses.ImportSiteList();
context.Entry(newItm).State = EntityState.Added;
context.Entry(newItm).CurrentValues.SetValues(ssItm);
context.SaveChanges();
Hope it helps.

Automatical creation of History in Entity framework

I'm using entity framework for first time. I have to create many entities(tables) with using of Entity Framework 6, is there any way how automatically create history table for all the entities and insert old version of a row into EntityHistory table whenever is row changed?
If i am not wrong we can manage it With the help of Entity Framework Snapshot History.
Click here to view the similar answer.
Disclaimer: I'm the owner of the project Entity Framework Plus
Documentations: EF+ Audit
This library allows you to audit & save information in a database with the AutoSavePreAction Action.
AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
// ADD "Where(x => x.AuditEntryID == 0)" to allow multiple SaveChanges with same Audit
(context as EntityContext).AuditEntries.AddRange(audit.Entries);
// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntityContext();
// ... ctx changes ...
var audit = new Audit();
audit.CreatedBy = "ZZZ Projects"; // Optional
ctx.SaveChanges(audit);
// Access to all auditing information
var entries = audit.Entries;
foreach(var entry in entries)
{
foreach(var property in entry.Properties)
{
}
}

Getting metadata in EF Core: table and column mappings

Looking to get metadata in EF Core, to work with the mappings of objects & properties to database tables & columns.
These mappings are defined in the DBContext.cs OnModelCreating() method, mapping tables with .ToTable(), and columns via .Property.HasColumnName().
But I don't see this metadata under the Entity Types returned by...
IEnumerable<IEntityType> entityTypes = [dbContext].Model.GetEntityTypes();
Is this metadata available anywhere in EF Core?
Is this metadata available anywhere in EF Core?
Yes it is. Just additionally to the properties examine the methods (GetXXX, FindXXX etc.). And pay special attention to Relational() extension methods.
For instance:
foreach (var entityType in dbContext.Model.GetEntityTypes())
{
var tableName = entityType.Relational().TableName;
foreach (var propertyType in entityType.GetProperties())
{
var columnName = propertyType.Relational().ColumnName;
}
}
You need to have Microsoft.EntityFrameworkCore.Relational Nuget package installed.
Update (EF Core 3.0+): Relational() provider extensions have been removed and properties have been replaced with direct Get / Set extension methods, so the code for column/table names now is simply
var tableName = entityType.GetTableName();
// ..
var columnName = propertyType.GetColumnName();
Update (EF Core 5.0+): Since now EF Core supports separate column name mappings for table, view, sql etc., you have to pass the desired StoreObjectIdentifier to GetColumnName method, e.g.
var tableName = entityType.GetTableName();
var tableIdentifier = StoreObjectIdentifier.Table(tableName, entityType.GetSchema());
// ...
var tableColumnName = propertyType.GetColumnName(tableIdentifier);

entity framework adding the contents of one data table to another one in the same database

How do I add the records of one data table to another with the entity framework?
With data sets its like:
private void sourceTabletransfer()
{
foreach (DataRow sourceTableRow in myDataSet.Tables["sourceTable"].Rows)
{
DataRow destinationTablerow = myDataSet.Tables["destinationTable"].NewRow();
destinationTablerow["date"] = sourceTableRow["date"];
destinationTablerow["varchar1"] = sourceTableRow["varchar1"];
destinationTablerow["int1"] = sourceTableRow["int1"];
myDataSet.Tables["destinationTable"].Rows.Add(destinationTablerow);
}
this.destinationTableBindingSource.EndEdit();
this.destinationTableTableAdapter.Update(myDataSet);
}
How do I do the above with the entity framework?
Thanks a lot in advance :)
Say you have two tables and their corresponding PoCo classes. Named them ParentEntity and ChildEntity.
foreach(var parentEntity in lstParentEntities)
{
ChildEntity child=new ChildEntity();
child.prop1=parentEntity.Prop1;
child.prop2=parentEntity.Prop2;
child.prop3=parentEntity.Prop3;
context.AddObject(child);
}
context.SaveChanges();
An Alternative -
Working with your POCO classes named Source and Destination;
context.Destination.Prop1 = Source.Prop1
context.SaveChanges();
Also - (I would add this as a comment if i had access to it :))
you need to use context.SaveChanges(), not context.Save()