ASP.NET web application + Entity Framework 4.0 with Concurrency Check - asp.net

I have an entity like this:
public class Player
{
[Required]
[Key]
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public string NativeCountry { get; set; }
[ConcurrencyCheck]
public DateTime LastModified { get; set; }
public virtual int TeamId { get; set; }
//navigational property
public virtual Team Team { get; set; }
public virtual ICollection<Tournament> Tournaments { get; set; }
}
this is how i configure Player entity:
public PlayerConfiguration()
{
Property(e => e.Id).IsRequired();
Property(e => e.FirstName).IsRequired().IsConcurrencyToken(true);
Property(e => e.NativeCountry).IsOptional();
Property(e => e.LastModified).IsOptional().IsConcurrencyToken(true);
HasRequired(e => e.Team).WithMany(s => s.Players).HasForeignKey(f => f.TeamId);
}
overridden OnModelCreating
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Configuration.ValidateOnSaveEnabled = false;
Configuration.LazyLoadingEnabled = true;
modelBuilder.Configurations.Add(new PlayerConfiguration());
modelBuilder.Configurations.Add(new TeamConfiguration());
modelBuilder.Configurations.Add(new TournamentConfiguration());
modelBuilder.Entity<Player>().ToTable("Player");
modelBuilder.Entity<Team>().ToTable("Team");
modelBuilder.Entity<Tournament>().ToTable("Tournament");
base.OnModelCreating(modelBuilder);
}
somewhere I do this to update a player:
db.Entry<Player>(player).State = System.Data.EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
}
when I try to update any given player at the same time, using two browsers, nothing happens. I don't want to use a TimeStamp annotation, because it will cost me one extra
column. How can I use the existing DateTime LastModified column to track concurrency.
I even tried making FirstName (and others) as ConcurrencyToken, but again nothing happened.
How does this [ConcurrencyCheck] work in asp.net web application.??
please help..

It looks like your code doesn't change LastModified property so you are using still the same concurrency token. That is a reason why people use Timestamp column because timestamp is automatically handled by database and you don't have to deal with it.
To use concurrency token your entity must follow very strict rules.
Your entity must hold old value of concurrency token (in case of ASP.NET it requires round tripping concurrency token to client and receiving it back with modified data).
If you don't use database generated concurrency token (timestamp or row version) you must set it manually each time you are going to change the record
If you work with detached entities the new token can be set only ofter you attach the entity to the context otherwise you will get exception every time you try to save updated data
Here is sample code to validate that concurrency checking works:
class Program
{
static void Main(string[] args)
{
using (var context = new Context())
{
context.Database.Delete();
context.Database.CreateIfNotExists();
context.Players.Add(new Player { FirstName = "ABC", LastName = "EFG", NativeCountry = "XYZ", LastModified = DateTime.Now});
context.SaveChanges();
}
using (var context = new Context())
{
var player = context.Players.First();
// Break here, go to database and change LastModified date
player.LastModified = DateTime.Now;
// If you changed LastModified date you will get an exception
context.SaveChanges();
}
}
}

this is what I did to make it work:
Player entity:
[ConcurrencyCheck]
public DateTime LastModified { get; set; }
in my code, onLoad of the form, called this function:
private static DateTime TimeStamp;
protected void LoadData()
{
Player player = new PlayerRepository().First(plyr => plyr.Id == Id);
if (player != null)
{
TimeStamp = player.LastModified;
//rest of the code
}
}
and upon click of the save button i.e. while updating entity:
protected void btnSave_Click(object sender, EventArgs e)
{
var playerRepo = new PlayerRepository();
var teamRepo = new TeamRepository();
if (Page.IsValid)
{
Player player;
if (this.Id == 0)//add
{
player = new Player();
//rest of the code
}
else //edit
player = playerRepo.First(p => p.Id == Id);
player.LastModified = DateTime.Now;
//custom logic
if (this.Id == 0) // add
{
playerRepo.Add(player);
playerRepo.SaveChanges();
}
else // edit
{
try
{
playerRepo.OriginalValue(player, "LastModified", TimeStamp);
playerRepo.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
//custom logic
}
}
}
and OriginalValue in the AbstractRepository is this:
public void OriginalValue(TEntity entity, string propertyName, dynamic value)
{
Context.Entry<TEntity>(entity).OriginalValues[propertyName] = value;
}
so explicitly i had to change the OriginalValue of the ConcurrencyCheck marked column to the older one.

Related

What would be the best/simplest solution to retrieve values from my database for comparison? - ASP.NET Core

I'm currently stuck on accessing all of the 'UserName' values from my database.
I am doing this so I can compare the user input for a username to check if it has been used before (I don't want two instances of the same username). This is on a .cshtml.cs page.
I am already able to access the database through my program, as create commands have been tested and do work.
My program is on ASP.NET 6.0 Core Web App.
I am a student with basic knowledge on ASP.NET Core, and on how to solve this issue, therefore as much simplified explanation would be very appreciated.
Here is my code:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using AQA_A_Level_CS_NEA__Suvat_Solver_.Models;
using AQA_A_Level_CS_NEA__Suvat_Solver_.Data;
namespace AQA_A_Level_CS_NEA__Suvat_Solver_.Pages.UserLogin
{
[BindProperties(SupportsGet = true)]
public class RegisterPageModel : PageModel
{
public new TempUserLoginModel TempUser { get; set; }
public bool HasPassword { get; set; } = true;
public bool HasUsername { get; set; } = true;
public bool UniUsername { get; set; } = true;
public bool RegisterApproved { get; set; } = false;
public bool AQAPhys { get; set; } = false;
public bool AQAMaths { get; set; } = false;
public bool SubjectChosen { get; set; } = true;
private readonly ApplicationDbContext _context;
public RegisterPageModel(ApplicationDbContext context)
{
_context = context;
}
public List<User> UserList = new List<User>();
public void OnGet()
{
}
public IActionResult OnPost()
{
User User = new User();
HasPassword = true;
HasUsername = true;
UniUsername = true;
SubjectChosen = true;
UserList = _context.User.ToList();
if (!AQAMaths && !AQAPhys)
{
SubjectChosen = false;
}
if (string.IsNullOrWhiteSpace(TempUser.Password) || TempUser.Password.Length < 4)
{
HasPassword = false;
}
if (string.IsNullOrWhiteSpace(TempUser.Username) || TempUser.Username.Length < 4)
{
HasUsername = false;
}
if (TempUser.Username == //database UserName value here )
{
//Here would be where the Username is compared
//UniUsername = false;
}
if (!HasPassword || !HasUsername || !UniUsername || !SubjectChosen)
{
return RedirectToPage("/UserLogin/RegisterPage", new { HasPassword, HasUsername, UniUsername, SubjectChosen });
}
else
{
RegisterApproved = true;
User.UserName = TempUser.Username;
User.UserPass = TempUser.Password;
User.UserCorrectAnsw = 0;
User.UserTotalAnsw = 0;
_context.User.Add(User);
_context.SaveChanges();
return RedirectToPage("/UserLogin/LoginPage", new { RegisterApproved });
}
}
}
}
Many Thanks.
Probably the strongest method is to enforce the user name column to be unique at the database level using a Unique Constraint. That way if you try to add a user with a duplicate user name, the database will simply return an error.
This article shows how to create a Unique Constraint with Entity Framework
You can be sure that the database will not allow a user with a duplicate user name with this method. However, trying to add a duplicate user will create an error which you will have to either handle or prevent from occurring in the first place (which is what you are doing now)
So for the code you are using now, since you already have the users pulled from the database here:
UserList = _context.User.ToList();
We can use LINQ to check if any of the users Usernames in UserList matches the TempUser like this:
if (UserList.Any(x => x.Username == TempUser.Username))
{
//Here would be where the Username is compared
UniUsername = false;
}
Since you didn't share your User model, this assumes your User class has a property named Username.
Happy Coding

Aspnetboilerplate application gives runtime error while applying sort on a query for ISoftDelete entity

I want to write CRUD services for an entity named Location . Location has a composite primary key, so I couldn't use AsyncCrudAppService and copied the methods that I wanted from AsyncCrudAppService.
When I use GetAll Service without ApplySorting method, it works fine. But when I add sorting, I get this runtime error:
[35] ERROR BookingSystem.middlewares.HttpGlobalExceptionFilter [(null)] - The LINQ expression 'DbSet
.Where(l => __ef_filter__p_0 || !(((ISoftDelete)l).IsDeleted))
.OrderByDescending(l => l.Id)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). S
ee https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
public class Location : IEntity<int>, IPassivable, IFullAudited<User> {
public int Id { get; set; }
public int IdLocation { get; set; } //primary key 0
public LocationType TypeId { get; set; } //primary key 1
public string Name { get; set; }
}
public interface ILocationService : IApplicationService
{
Task<PagedResultDto<LocationDto>> GetAllAsync(PagedLocationResultRequestDto input);
}
public class LocationService : AbpServiceBase, ILocationService, IPerWebRequestDependency
{
private readonly IRepository<Location, int> _repository;
private IAsyncQueryableExecuter AsyncQueryableExecuter { get; set; }
public LocationService(IRepository<Location> repository)
{
_repository = repository;
AsyncQueryableExecuter = NullAsyncQueryableExecuter.Instance;
}
public async Task<PagedResultDto<LocationDto>> GetAllAsync(PagedLocationResultRequestDto input)
{
if (input.MaxResultCount > _appSettings.Value.MaxResultCount)
{
throw new BookingSystemUserFriendlyException(BookingSystemExceptionCode.InputNotValid,
nameof(input.MaxResultCount));
}
var query = CreateFilteredQuery(input);
var totalCount = await AsyncQueryableExecuter.CountAsync(query);
query = ApplySorting(query, input);
query = ApplyPaging(query, input);
var entities = await AsyncQueryableExecuter.ToListAsync(query);
return new PagedResultDto<LocationDto>(
totalCount,
entities.Select(MapToEntityDto).ToList()
);
}
protected virtual IQueryable<Location> ApplySorting(
IQueryable<Location> query, PagedLocationResultRequestDto input)
{
if (input is ISortedResultRequest sortInput &&
!sortInput.Sorting.IsNullOrWhiteSpace())
{
return query.OrderBy(sortInput.Sorting);
}
return query.OrderByDescending(e => e.Id);
}
protected virtual IQueryable<Location> ApplyPaging(
IQueryable<Location> query, PagedLocationResultRequestDto input)
{
if (input is IPagedResultRequest pagedInput)
{
return query.PageBy(pagedInput);
}
return query;
}
private IQueryable<Location> CreateFilteredQuery(PagedLocationResultRequestDto input)
{
return _repository.GetAll()
.WhereIf(!string.IsNullOrWhiteSpace(input.Name),
location => location.Name.ToLower().Contains(input.Name.Trim().ToLower()));
}
private LocationDto MapToEntityDto(Location entity)
{
return ObjectMapper.Map<LocationDto>(entity);
}
}
Abp package version: 5.1.0
Base framework: .Net Core
Well, I asked the same question in the project's GitHub and got the answer.
In ApplySorting, the default sorting is based on Id, which doesn't exist in my database table.
If you are using composite PK, then you probably don't have the Id field in the database, right? Then you should not sort by Id.
https://github.com/aspnetboilerplate/aspnetboilerplate/issues/5274#issuecomment-583946065

How to store unique class instances in SQLite?

I'm trying to store some information as a class instance in a SQLite table. The instances need to be unique in their DateTime property. I'm completely new to database programming, and I don't really understand how use SQLite in Xamarin. As new instances are created they need to update the existing instances in the table if they match in their DateTime property.
SQLiteAsyncConnection connection = new SQLiteAsyncConnection(App.FilePath);
await connection.CreateTableAsync<ModulInformationData>();
ModulInformationData data = new ModulInformationData();
data.InitModulInformation(modul);
int rows = 0;
try
{
rows = await connection.UpdateAsync(data);
}catch(Exception e)
{
Console.WriteLine("SQL Update failed " + e.Message);
}
Console.WriteLine("rows updated: " + rows);
if (rows == 0)
{
Console.WriteLine("before insert");
try
{
int key1 = await connection.InsertAsync(data);
Console.WriteLine("after insert: " + key1);
}catch (Exception e)
{
Console.WriteLine("SQL insert failed " + e.Message);
}
}
The ModulInformationData class
public class ModulInformationData
{
[PrimaryKey,AutoIncrement]
public int Id { get; set; }
[Unique]
public DateTime tidspunkt { get; set; }
other properties...
At the moment, I'm catching an error when inserting, but the message only says 'Constraint'. What can I do to make this work?
Do you want to achieve the result like this GIF。
First of all, you can create a class for the database CRUD.
public class NoteDatabase
{
readonly SQLiteAsyncConnection _database;
public NoteDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Note>().Wait();
}
public Task<List<Note>> GetNotesAsync()
{
return _database.Table<Note>().ToListAsync();
}
public Task<Note> GetNoteAsync(int id)
{
return _database.Table<Note>()
.Where(i => i.ID == id)
.FirstOrDefaultAsync();
}
public Task<int> SaveNoteAsync(Note note)
{
if (note.ID != 0)
{
return _database.UpdateAsync(note);
}
else
{
return _database.InsertAsync(note);
}
}
public Task<int> DeleteNoteAsync(Note note)
{
return _database.DeleteAsync(note);
}
}
Then there is model class.
public class Note
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Text { get; set; }
[Unique]
public DateTime Date { get; set; }
public string Gender { get; set; }
}
If we want to add or update the data to the database, firstly, we should update the data to the instance, then we could just save this instance to the database like following save click event.
async void OnSaveButtonClicked(object sender, EventArgs e)
{
var note = (Note)BindingContext;
note.Date = DateTime.UtcNow;
note.Gender = (string)myPicker.SelectedItem;
await App.Database.SaveNoteAsync(note);
await Navigation.PopAsync();
}
Here is my demo. you can download it and refer to it.
https://github.com/851265601/databaseDemo

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

I am working with Entity Framework Code First and MVC 5. When I created my application with Individual User Accounts Authentication I was given an Account controller and along with it all the required classes and code that is needed to get the Indiv User Accounts authentication to work.
Among the code already in place was this:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DXContext", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
But then I went ahead and created my own context using code first, so I now have the following too:
public class DXContext : DbContext
{
public DXContext() : base("DXContext")
{
}
public DbSet<ApplicationUser> Users { get; set; }
public DbSet<IdentityRole> Roles { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Paintings> Paintings { get; set; }
}
Finally I have the following seed method to add some data for me to work with whilst developing:
protected override void Seed(DXContext context)
{
try
{
if (!context.Roles.Any(r => r.Name == "Admin"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "Admin" };
manager.Create(role);
}
context.SaveChanges();
if (!context.Users.Any(u => u.UserName == "James"))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser { UserName = "James" };
manager.Create(user, "ChangeAsap1#");
manager.AddToRole(user.Id, "Admin");
}
context.SaveChanges();
string userId = "";
userId = context.Users.FirstOrDefault().Id;
var artists = new List<Artist>
{
new Artist { FName = "Salvador", LName = "Dali", ImgURL = "http://i62.tinypic.com/ss8txxn.jpg", UrlFriendly = "salvador-dali", Verified = true, ApplicationUserId = userId },
};
artists.ForEach(a => context.Artists.Add(a));
context.SaveChanges();
var paintings = new List<Painting>
{
new Painting { Title = "The Persistence of Memory", ImgUrl = "http://i62.tinypic.com/xx8tssn.jpg", ArtistId = 1, Verified = true, ApplicationUserId = userId }
};
paintings.ForEach(p => context.Paintings.Add(p));
context.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var validationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
My solution builds fine, but when I try and access a controller that requires access to the database I get the following error:
DX.DOMAIN.Context.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
DX.DOMAIN.Context.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
What am I doing wrong? Is it because I have two contexts?
UPDATE
After reading Augusto's reply, I went with Option 3. Here is what my DXContext class looks like now:
public class DXContext : DbContext
{
public DXContext() : base("DXContext")
{
// remove default initializer
Database.SetInitializer<DXContext>(null);
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Painting> Paintings { get; set; }
public static DXContext Create()
{
return new DXContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
}
public DbQuery<T> Query<T>() where T : class
{
return Set<T>().AsNoTracking();
}
}
I also added a User.cs and a Role.cs class, they look like this:
public class User
{
public int Id { get; set; }
public string FName { get; set; }
public string LName { get; set; }
}
public class Role
{
public int Id { set; get; }
public string Name { set; get; }
}
I wasn't sure if I would need a password property on the user, since the default ApplicationUser has that and a bunch of other fields!
Anyways, the above change builds fine, but again I get this error when the application is ran:
Invalid Column name UserId
UserId is an integer property on my Artist.cs
In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class's OnModelCreating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); // I had removed this
/// Rest of on model creating here.
}
Which then fixed up my missing indexes from the identity classes and I could then generate migrations and enable migrations appropriately.
The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:
IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }
and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:
modelBuilder.Entity<TUserRole>()
.HasKey(r => new {r.UserId, r.RoleId})
.ToTable("AspNetUserRoles");
modelBuilder.Entity<TUserLogin>()
.HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
.ToTable("AspNetUserLogins");
and as your DXContext doesn't derive from it, those keys don't get defined.
If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework, you will understand everything.
I came across this situation some time ago, and I found three possible solutions (maybe there are more):
Use separate DbContexts against two different databases or the same database but different tables.
Merge your DXContext with ApplicationDbContext and use one database.
Use separate DbContexts against the same table and manage their migrations accordingly.
Option 1:
See update the bottom.
Option 2:
You will end up with a DbContext like this one:
public class DXContext : IdentityDbContext<User, Role,
int, UserLogin, UserRole, UserClaim>//: DbContext
{
public DXContext()
: base("name=DXContext")
{
Database.SetInitializer<DXContext>(null);// Remove default initializer
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public static DXContext Create()
{
return new DXContext();
}
//Identity and Authorization
public DbSet<UserLogin> UserLogins { get; set; }
public DbSet<UserClaim> UserClaims { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
// ... your custom DbSets
public DbSet<RoleOperation> RoleOperations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
// Configure Asp Net Identity Tables
modelBuilder.Entity<User>().ToTable("User");
modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);
modelBuilder.Entity<Role>().ToTable("Role");
modelBuilder.Entity<UserRole>().ToTable("UserRole");
modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
}
}
Option 3:
You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:
public class DXContext : DbContext
{
public DXContext()
: base("name=DXContext") // connection string in the application configuration file.
{
Database.SetInitializer<DXContext>(null); // Remove default initializer
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
// Domain Model
public DbSet<User> Users { get; set; }
// ... other custom DbSets
public static DXContext Create()
{
return new DXContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
modelBuilder.Entity<User>().ToTable("User");
}
public DbQuery<T> Query<T>() where T : class
{
return Set<T>().AsNoTracking();
}
}
where User is:
public class User
{
public int Id { get; set; }
[Required, StringLength(100)]
public string Name { get; set; }
[Required, StringLength(128)]
public string SomeOtherColumn { get; set; }
}
With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.
Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts
You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:
//CreateTable(
// "dbo.User",
// c => new
// {
// Id = c.Int(nullable: false, identity: true),
// Name = c.String(nullable: false, maxLength: 100),
// SomeOtherColumn = c.String(nullable: false, maxLength: 128),
// })
// .PrimaryKey(t => t.Id);
AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));
and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:
public static class DXDatabaseMigrator
{
public static string ExecuteMigrations()
{
return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
ExecuteDXMigrations());
}
private static string ExecuteIdentityMigrations()
{
IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
return RunMigrations(configuration);
}
private static string ExecuteDXMigrations()
{
DXMigrationConfiguration configuration = new DXMigrationConfiguration();
return RunMigrations(configuration);
}
private static string RunMigrations(DbMigrationsConfiguration configuration)
{
List<string> pendingMigrations;
try
{
DbMigrator migrator = new DbMigrator(configuration);
pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed
if (pendingMigrations.Any())
migrator.Update();
}
catch (Exception e)
{
ExceptionManager.LogException(e);
return e.Message;
}
return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
}
}
This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.
Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.
UPDATE: Expand Option 1
For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:
public class AppUser : TrackableEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
// This Id is equal to the Id in the AspNetUser table and it's manually set.
public override int Id { get; set; }
(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)
I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:
IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);
if (!identityResult.Succeeded)
throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));
AppUser appUser;
try
{
appUser = RegisterInAppUserTable(model, aspNetUser);
}
catch (Exception)
{
// Roll back
UserManager.Delete(aspNetUser);
throw;
}
(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)
The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):
public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
public IdentityMigrationConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(IdentityContext context)
{
}
}
This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.
By Changing The DbContext As Below;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
Just adding in OnModelCreating method call to base.OnModelCreating(modelBuilder); and it becomes fine. I am using EF6.
Special Thanks To #The Senator
For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string to either int or Guid, if you're still getting
EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.
EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.
you probably just forgot to specify the new key type on IdentityDbContext:
public class AppIdentityDbContext : IdentityDbContext<
AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
public AppIdentityDbContext()
: base("MY_CONNECTION_STRING")
{
}
......
}
If you just have
public class AppIdentityDbContext : IdentityDbContext
{
......
}
or even
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
......
}
you will get that 'no key defined' error when you are trying to add migrations or update the database.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
// relationship.DeleteBehavior = DeleteBehavior.Restrict;
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<IdentityRole<string>>().ToTable("Roles");
modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims");
modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");
}
}
My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)
[Table("UserOtherEntity")]
public partial class UserOtherEntity
{
public Guid UserOtherEntityId { get; set; }
[Required]
[StringLength(128)]
public string UserId { get; set; }
[Required]
public Guid OtherEntityId { get; set; }
public virtual OtherEntity OtherEntity { get; set; }
}
public partial class UserOtherEntity : DataManager
{
public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
{
return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
}
}
public partial class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
[NotMapped]
public IEnumerable<OtherEntity> OtherEntities
{
get
{
return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
}
}
}

EF Code First + remove orphans which marked as Modified (IsDeleted = 1)

I have the next problem. My code context + model:
public class MediaPlanContext : DbContext
{
public MediaPlanContext() : base(lazyLoading:false) {}
public DbSet<MediaPlan> MediaPlan { get; set; }
public DbSet<MovieType> MovieType { get; set; }
public DbSet<MediaPlanItem> MediaPlanItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder
.Entity<MediaPlanItem>()
.HasKey(mpi => new {mpi.Id, mpi.MediaPlanId});
modelBuilder
.Entity<MediaPlanItem>()
.Property(mpi => mpi.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder
.Entity<MediaPlan>()
.HasMany(mp => mp.MediaPlanItems)
.WithRequired()
.HasForeignKey(mpi => mpi.MediaPlanId)
.WillCascadeOnDelete();
}
}
public class MediaPlan : IBaseObject
{
public virtual ICollection<MediaPlanItem> MediaPlanItems { get; set; }
}
public class MediaPlanItem : IBaseObject
{
public int MediaPlanId {get;set;}
public MediaPlan MediaPlan {get;set;}
}
public interface IBaseObject
{
public int Id {get;}
public DateTime DateCreated {get;}
public DateTime DateModified {get;set;}
}
Also I use repository to handle with my objects (IBaseObject-s) with root-object MediaPlan.
When object in my DB will become deleted I mark entity (record) as IsDeleted = 1 and I have some logic in my repository class to handle regular delete as update, change EntityState to Modified instead of Deleted.
Problem with the next code:
var rep = new MediaPlanRepository(new MediaPlanContext());
var withItems = rep.GetWithMediaPlanItems();
var m1 = withItems.First();
var mpi1 = m1.MediaPlanItems.First();
m1.MediaPlanItems.Remove(mpi1); // 6 items before remove
// 5 items after remove
rep.SaveChanges();
// 6 items after save changes :(
Question: Can I handle the moment after saveChanges occurs and detach my IsDeleted = 1 entity? Is is resolve my problem?
Remark: Related entities loaded to root object as projection and as Julie says in paragraph 'Scenario When This May Not Work As Expected' can produce problems with entities that is already tracked by context.
Code:
public override int SaveChanges()
{
var result = base.SaveChanges();
// AfterSave code
var isDeletedEntities = EfContext.ChangeTracker
.Entries()
.Select(dbE => new {
DBEntity = dbE,
BaseObject = (dbE.Entity as IBaseObject)})
.Where(dbe => dbe.BaseObject.IsDeleted);
foreach (var isDeletedEntity in isDeletedEntities)
{
isDeletedEntity.DBEntity.State = EntityState.Detached;
}
}

Resources