SQL to INSERT file to table
I use this snippet to add any kinds of files to my database table which has a "image" data type.
public interface IContextConfig
{
string ConnectionString { get; }
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using NEISTracker.Data.Interfaces;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MyProject.Data
{
public partial class MyDBContext : DbContext
{
private readonly string _connectionString;
public MyDBContext(IContextConfig contextConfig)
{
_connectionString = contextConfig.ConnectionString;
}
public int UserID { get; set; }
public override int SaveChanges()
{
UpdateAuditFields();
return base.SaveChanges();
}
public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
UpdateAuditFields();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
private void UpdateAuditFields()
{
foreach (var entry in ChangeTracker.Entries())
{
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
foreach (var property in entry.Properties)
{
var propertyName = property.Metadata.Name.ToLower();
if (entry.State == EntityState.Modified)
{
if (propertyName == "lastupdatedbyuserid")
{
property.CurrentValue = UserID; //userid
}
else if (propertyName == "lastupdateddate")
{
property.CurrentValue = DateTime.Now;
}
}
else //it's an insert...
{
if (propertyName == "createdbyuserid")
{
property.CurrentValue = UserID;
}
else if (propertyName == "createddate")
{
property.CurrentValue = DateTime.Now;
}
}
}
}
}
}
}
}
IContextConfig config = new ContextConfig();
var context = new MyDBContext(config);
context.UserID = 2; //2 is just a made up value, you need to dynamically pass the current user.
context.SaveChanges();
Comments
Post a Comment