Using .Net Core 2.1 and Audit.NET EF 12.1.10, I'm trying to add a migration that includes the audit tables but when invoking Add-Migration, no audit tables are generated in the migration. I assumed that using the "dynamic" audit will do this automagically. I don't have any audit interfaces-- I am leaving this up to Audit.NET. Below is in my Startup:
var serviceProvider = services.BuildServiceProvider();
Audit.EntityFramework.Configuration.Setup()
.ForContext<MainDbContext>(config => config
.IncludeEntityObjects()
.AuditEventType("{context}:{database}"))
.UseOptOut()
.IgnoreAny(entity => entity.Name.StartsWith("AspNet") && entity.Name.StartsWith("OI"));
Audit.Core.Configuration.Setup()
.UseEntityFramework(ef => ef
.AuditTypeNameMapper(typeName => "Audit_" + typeName)
.AuditEntityAction((evt, entry, auditEntity) =>
{
// Get the current HttpContext
var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
// Store the identity name on the "UserName" property of the audit entity
((dynamic)auditEntity).UserName = httpContext.User?.Identity.Name;
((dynamic)auditEntity).AuditDate = DateTime.UtcNow;
((dynamic)auditEntity).AuditAction = entry.Action;
}));
My DbContext extending from AuditIdentityDbContext:
public class MainDbContext : AuditIdentityDbContext<User, Role, string>
I only have one entity so far, called Activity, just to test this out and I would expect Add-Migrations to include an Audit_Activity table as well as the Activity table, but I only got the latter. Not sure what I'm doing wrong here.
I tried Auditing Identity Roles just because it was easiest to test at the moment
public class ApplicationRole : IdentityRole
{
}
public class Audit_ApplicationRole : IAudit
{
[Key]
public string Id { get; set; }
[Column(TypeName = "NVARCHAR(256)")]
public string Name { get; set; }
[Column(TypeName = "NVARCHAR(256)")]
public string NormalizedName { get; set; }
public string ConcurrencyStamp { get; set; }
public ApplicationRole Role { get; set; }
public string RoleId { get; set; }
[Column(TypeName = "VARCHAR(100)")]
public string AuditUser { get; set; }
public DateTime AuditDate { get; set; }
[Column(TypeName = "VARCHAR(7)")]
public string Action { get; set; } // "Insert", "Update" or "Delete"
}
public interface IAudit
{
string AuditUser { get; set; }
DateTime AuditDate { get; set; }
string Action { get; set; }
}
Then I used your code in StartUp.cs
Audit.EntityFramework.Configuration.Setup()
.ForContext<ApplicationDbContext>(config => config
.IncludeEntityObjects()
.AuditEventType("{context}:{database}"));
Audit.Core.Configuration.Setup()
.UseEntityFramework(x => x
.AuditTypeNameMapper(typeName => "Audit_" + typeName)
.AuditEntityAction<IAudit>((ev, ent, auditEntity) =>
{
auditEntity.AuditDate = DateTime.UtcNow;
auditEntity.AuditUser = ev.Environment.UserName;
auditEntity.Action = ent.Action;
}));
What I found out is that the Id had to be string for some reason, it could not be int.
Screenshot from the link shows that the changes in data have saved.
enter image description here
On the side note, I wanted to save the user logged in via Identity, so in case anyone wondering, this post helped me achieve it.
https://entityframeworkcore.com/knowledge-base/49799223/asp-net-core-entity-changing-history
Related
working my way through an EF core project I have inherited and am quite new when it comes to LINQ/EF core.
I'll cut this back to simplify things, and will demonstrate my problem with 4 basic tables.
Customer
CustomerId
Name
Contact
1
John
john#gmail.com
2
Peter
peter#gmail.com
CustomerTrade
Id
CustomerId
OtherDetail
T1
1
xyz
T2
1
abc
CustomerTradeParameter
ParamID
TradeId
Value
X
1
1234
Y
1
5678
CustomerTradeParameterType
ParamID
Name
OtherGenericInfo
X
Hello
Null
Y
Test
Null
Models
public class Customer : AuditableEntity
{
public long CustomerId { get; private set; }
public string Name { get; private set; }
public string Contact { get; private set; }
public virtual ICollection<CustomerTrade> CustomerTradeList{ get; set; }
protected Customer()
{ }
public class CustomerTrade : AuditableEntity
{
public long Id { get; private set; }
public long CustomerId { get; private set; }
public string OtherDetail { get; private set; }
public virtual ICollection<CustomerTradeParameter> CustomerTradeParameterList { get; set; } = new List<CustomerTradeParameter>();
protected CustomerTrade() // For EF Core
{ }
public class CustomerTradeParameter : AuditableEntity
{
public long TradeId { get; set; }
public string ParameterType { get; private set; }
public string Value{ get; private set; }
protected CustomerTradeParameter() // For EF Core
{ }
}
DTOs
public class CustomerTradeDto : AuditableDto
{
public long Id { get; set; }
public long CustomerId { get; set; }
public virtual ICollection<CustomerTradeParameterDto> CustomerTradeParameterList { get; set; } = new List<CustomerTradeParameterDto>();
}
public class CustomerTradeParameterDto : AuditableDto
{
public long TradeId { get; set; }
public string ParameterType { get; set; }
public string Value { get; set; }
}
The below query is attempting to retrieve a specific trade, and a list of its relevant parameters.
IQueryable<CustomerTradeDto> foundTrade = _database.CustomerTrade
.Select(trade => new CustomerTradeDto
{
Id = trade.Id,
CustomerId = trade.CustomerId,
CustomerTradeParameterList = trade.CustomerTradeParameterList.Select(param => new CustomerTradeParameterDto{
ParameterType = param.ParameterType,
TradeId = customerTrade.Id,
Value = param.Value
// (second question written further below) - If I wanted to additionally retrieve the CustomerTradeParameterType record
// (to get the name of this parameter), how would I embed this join?
// I originally had ParameterType defined as a "CustomerTradeParameterType" instead of a string,
// but am not sure how to add this extra join inside this select?
}).ToList()
})
.Where(e => e.Id == find.Id);
The .Select on CustomerTradeParameterList is raising the following error:
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'CustomerTradeId'.
I understand EF core is attempting to define a column that it is unsure of, but I am not sure how to fix this? The correct column is TradeId.
Secondly, I have an additional question regarding joins inside a sub .Select. In the query above I have a comment outlining the question.
Appreciate any tips you can provide!
I want to update an entity in database. I use the aspnetboilerplate template project. I have a method UpdateAsset in the application layer:
public async Task UpdateAsset(UpdateAssetInput input)
{
var asset = ObjectMapper.Map<Asset>(input.Asset);
asset.Domain = asset.Domain.ToLowerInvariant();
// Update Twitter Id
var twitterName = input.Asset.SocialAccounts?.TwitterInfo?.Name;
if (twitterName != null)
{
var twitterId = await _twitterActivityManager.GetTwitterIdByTwitterName(twitterName);
if (twitterId != null)
{
input.Asset.SocialAccounts.TwitterInfo.Id = twitterId;
}
}
asset.SetData<SocialAccounts>(AssetExtensionData.SocialAccounts, input.Asset.SocialAccounts);
var connectedAsset = await _assetManager.GetAsset(input.Asset.LockedPositionInfo.ConnectedAssetId);
if (connectedAsset != null)
{
input.Asset.LockedPositionInfo.ConnectedAssetUnit = connectedAsset.Unit;
}
asset.SetData<LockedPositionInfo>(AssetExtensionData.LockedPositionInfo, input.Asset.LockedPositionInfo);
asset.SetData(AssetExtensionData.WithdrawalApiInfo, input.Asset.WithdrawalApiInfo);
await _assetManager.UpdateAsset(asset);
}
UpdateAssetInput:
public class UpdateAssetInput
{
public AssetDto Asset { get; set; }
}
AssetDto:
[AutoMap(typeof(Asset))]
public class AssetDto : AuditedEntityDto<string>
{
public const int SYMBOL_LENGTH = 10;
[Required]
[MaxLength(SYMBOL_LENGTH)]
public new string Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public string Website { get; set; }
[Required]
public string Domain { get; set; }
public string Logo { get; set; }
public string Organization { get; set; }
public string Unit { get; set; }
public SocialAccounts SocialAccounts { get; set; }
public LockedPositionInfo LockedPositionInfo { get; set; }
public WithdrawalApiInfo WithdrawalApiInfo { get; set; }
public decimal TotalAmount { get; set; }
public decimal Price { get; set; }
public bool IsDisable { get; set; } = false;
}
UpdateAsset in the AssetManager:
public async Task UpdateAsset(Asset asset)
{
try
{
await _assetRepository.UpdateAsync(asset);
}
catch (Exception e)
{
Logger.Error(e.Message, e);
throw new UserFriendlyException(L("AssetUpdateFailed"), asset.Name);
}
}
When I call the UpdateAsset of the application layer in front end, I get the exception:
System.InvalidOperationException: 'The instance of entity type 'Asset' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
So how to solve the problem ?
Normally, when we update a asset entity, we will do following 3 steps:
Get asset entity from db
set updated value to asset entity
Update asset entity
based on your error message, you may get asset entity from db twice
Get asset1 entity from db - tracked
Get asset2 entity from db - tracked
set updated value to asset2 entity
Update asset2 entity
Please check if you have above code snippet
I am struggling to get an Item by ID using the asynchronous API of SQLite.Net Async PCL. Here is my model class
public class Invoice : IEntityBase
{
public Invoice()
{
LineItems = new List<LineItem>();
DateCreated = DateTime.Now;
}
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
public DateTime DateCreated { get; set; }
public int Term { get; set; }
public bool Paid { get; set; }
public decimal Total { get; set; }
public string Notes { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<LineItem> LineItems { get; set; }
}
And the LineItems that has a One to Many relationship here
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public int Qty { get; set; }
[ForeignKey(typeof(Invoice))]
public int InvoiceId { get; set; }
[ManyToOne]
public Invoice Invoice { get; set; }
Here is the constructor:
public SQLiteAsyncConnection DbConnection;
public InvoiceDatabase(ISQLitePlatform platform, string databasePath)
{
if (DbConnection == null)
{
var connectionAsync = new Func<SQLiteConnectionWithLock>(() =>
new SQLiteConnectionWithLock
(
platform,
new SQLiteConnectionString(databasePath, false)
)
);
DbConnection = new SQLiteAsyncConnection(connectionAsync);
DbConnection.CreateTableAsync<Invoice>();
DbConnection.CreateTableAsync<LineItem>();
}
}
Other CRUD methods (Insert, GetALL) is working except getting an Invoice by ID, and both Visual Studio and Xamarin Studio are not giving me any useful stacktrace.
Here is the Get Method
private readonly InvoiceDatabase _database;
public InvoiceRepository(ISQLitePlatform platform, string databasePath)
{
if (_database == null)
{
_database = new InvoiceDatabase(platform, databasePath);
}
}
public async Task<Invoice> GetInvoice(int id)
{
var result = await _database.DbConnection.Table<Invoice>()
.Where(t => t.Id == id)
.FirstOrDefaultAsync();
return result;
}
I am passing in the Android implementation of SQLite, and like I said the Database is created but I am unable to get the Invoice object back, I even tried
public Task<Invoice> GetInvoiceWithChildren(int id)
{
return _database.DbConnection.GetWithChildrenAsync<Invoice>(id);
}
Any Help will be greatly appreciated.
After three days of chasing shadows it turned out that it is just a very simple thing that is tripping me up. I am tying to save a List of objects like so
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<LineItem> LineItems { get; set; }
I missed the part of the documentation that repeats the fact that SQLite.Net is a lightweight ORM - that point could not be stressed enough so you will have to remove your full size ORM hats such EF. So after reading from the SQLite-Net Extension documentation which says
Text blobbed properties
Text-blobbed properties are serialized into a text property when saved and deserialized when loaded. This allows storing simple objects in the same table in a single column.
Text-blobbed properties have a small overhead of serializing and deserializing the objects and some limitations, but are the best way to store simple objects like List or Dictionary of basic types or simple relationships.
I change my proptery like so and everything is now working as expected. Off now to dealing with the nuances of Async and Await
[TextBlob("LineItemBlobbed")]
public List<LineItem> LineItems { get; set; }
public string LineItemBlobbed { get; set; }
I´m started to work with AutoMapper today...
But I´m having some problem with Dropdown model...
What I have so far :
User Model
public class User : Entity
{
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual Role Role { get; set; }
}
Role Model
public class Role : Entity
{
public virtual string Name { get; set; }
}
UserUpdateViewModel
public class UserUpdateViewModel
{
public int Id{get;set;}
[Required(ErrorMessage = "Required.")]
public virtual string Name { get; set; }
[Required(ErrorMessage = "Required."), Email(ErrorMessage = "Email Invalid."), Remote("EmailExists", "User", ErrorMessage = "Email already in use.")]
public virtual string Email { get; set; }
[Required(ErrorMessage = "Required.")]
public virtual string Password { get; set; }
[Required(ErrorMessage = "Required")]
public virtual string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Required.")]
public int RoleId { get; set; }
public IList<Role> Roles { get; set; }
}
UserController
public ActionResult Update(int id=-1)
{
var _user = (_userRepository.Get(id));
if (_user == null)
return RedirectToAction("Index");
Mapper.CreateMap<User, UserUpdateViewModel>();
var viewModel = Mapper.Map<User, UserUpdateViewModel>(_user);
viewModel.Roles = _roleRepository.GetAll();
return View(viewModel);
}
[HttpPost, Transaction]
public ActionResult Update(UserViewModel user)
{
if (ModelState.IsValid)
{
user.Password = _userService.GetPasswordHash(user.Password);
Mapper.CreateMap<UserViewModel, User>();
var model = Mapper.Map<UserViewModel, User>(user); //model.Role = null
_userRepository.SaveOrUpdate(model); //ERROR, because model.Role = null
return Content("Ok");
}
return Content("Erro").
}
View Update
...
#Html.DropDownListFor(model => model.RoleId, new SelectList(Model.Roles, "Id", "Name"), "-- Select--", new { #class = "form radius" })
...
Some considerations:
1 - I´m returning Content() because is all Ajax enabled using HTML 5 PushState etc etc
2 - In my Update(POST one) method, my model returned by Autommapper has Role = null
Why my Role returned by Automapper is null?
Is that the right way to work with AutoMapper? Any tip?
Thanks
The map is failing because you are trying to map a single Role directly to a collection of Roles. And a collection of Roles back to a single Role. You cant directly map between these as they are different types.
If you wanted to map a Role to a List then you could use a custom value resolver.
Mapper.CreateMap<User , UserUpdateViewModel>()
.ForMember(dest => dest.Roles, opt => opt.ResolveUsing<RoleToCollectionResolver>())
Public class RoleToCollectionResolver: ValueResolver<User,IList<Role>>{
Protected override IList<Role> ResolveCore(User source){
var roleList = new List<Role>();
roleList.Add(source.Role);
Return roleList;
}
}
I'm using Entity Framework 4 CTP5 Code First and I have a model along the lines of:
public class User {
public int UserId { get; set; }
public string Email { get; set; }
public ICollection<Customer> TaggedCustomers { get; set; }
}
public class Customer {
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<User> TaggedBy { get; set; }
}
There is a many to many relationship where a User can 'tag' a Customer and a Customer can be 'tagged' by many users. I have a working DbContext and I can query customers using
var customers = DbContext.Customers.Include(c => c.TaggedBy);
But each customer will have all users that have tagged the customer. How do I restrict the TaggedBy collection to just result with a specifed UserId?
I've tried along the lines of DbContext.Customers.Include(c => c.TaggedBy.Select(x => x.Id == userId)); but that throws an error.
EF Feature CTP5: Fluent API Samples - ADO.NET team blog - Site Home - MSDN Blogs
modelBuilder.Entity<Product>()
.HasMany(p => p.Tags)
.WithMany(t => t.Products)
.Map(m =>
{
m.MapLeftKey(p => p.ProductId, "CustomFkToProductId");
m.MapRightKey(t => t.TagId, "CustomFkToTagId");
});
Code First Mapping Changes in CTP5 - ADO.NET team blog - Site Home - MSDN Blogs
modelBuilder.Entity<Product>()
.HasMany(p => p.SoldAt)
.WithMany(s => s.Products)
.Map(mc => {
mc.ToTable("ProductsAtStores");
mc.MapLeftKey(p => p.Id, "ProductId");
mc.MapRightKey(s => s.Id, "StoreId");
});
Mark your collections as virtual and then you can easily do:
public class User
{
public int UserId { get; set; }
public string Email { get; set; }
public virtual ICollection<Customer> TaggedCustomers { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<User> TaggedBy { get; set; }
}
using(var context = new MyDbContext())
{
var user = context.Users.Single(o => o.UserId == 0);
var customers = user.TaggedCustomers;
}
Results in much cleaner code in my opinion.