Merge ApplicationDbContext with my custom DbContext - entity-framework

I need to merge my ApplicationDbContext with my DemoPoolEntities context. What do I need to do to to properly merge the two? The reason I need to do this is so that I can access the ApplicationUser data from the Customer class which is a part of the DemoPoolEntities context. I am not sure where to start to merge these two so they are both in one DbContext.
ApplicationDbContext
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace DemoPool.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public 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;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DemoPoolEntities", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
DemoPoolEntities
namespace DemoPool.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.AspNet.Identity.EntityFramework;
public partial class DemoPoolEntities : DbContext
{
public DemoPoolEntities()
: base("name=DemoPoolEntities")
{
}
public virtual DbSet<Condition> Conditions { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Kit> Kits { get; set; }
public virtual DbSet<Loan> Loans { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Type> Types { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Condition>()
.Property(e => e.Condition1)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.CompanyName)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.FirstName)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.LastName)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.PhoneNumber)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.Email)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.Address1)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.Address2)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.City)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.State)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.Zip)
.IsUnicode(false);
modelBuilder.Entity<Kit>()
.Property(e => e.KitName)
.IsUnicode(false);
modelBuilder.Entity<Loan>()
.Property(e => e.TrackingNumber)
.IsUnicode(false);
modelBuilder.Entity<Product>()
.Property(e => e.ProductName)
.IsUnicode(false);
modelBuilder.Entity<Product>()
.Property(e => e.Description)
.IsUnicode(false);
modelBuilder.Entity<Product>()
.Property(e => e.ProductNumber)
.IsUnicode(false);
modelBuilder.Entity<Product>()
.Property(e => e.SerialNumber)
.IsUnicode(false);
modelBuilder.Entity<Product>()
.Property(e => e.Manufacturer)
.IsUnicode(false);
modelBuilder.Entity<Type>()
.Property(e => e.Type1)
.IsUnicode(false);
modelBuilder.Entity<IdentityUserLogin>()
.HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>()
.HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
}
}

DemoPoolEntities need to inherit from ApplicationDbContext
public partial class DemoPoolEntities : ApplicationDbContext
{
...
}

Related

Can't define composite key in my EF Core database-first ASP.NET Core Web API

I have following model of a table:
public partial class FlightsOfTicket
{
public int TicketId { get; set; }
public int FlightId { get; set; }
public int PlaneId { get; set; }
public int FlightNumber { get; set; }
public bool? IsDirect { get; set; }
public virtual Flight Flight { get; set; }
public virtual Plane Plane { get; set; }
public virtual Ticket Ticket { get; set; }
}
And my DbContext has the following code:
modelBuilder.Entity<FlightsOfTicket>(entity =>
{
entity.HasKey(e => new { e.TicketId, e.FlightId, e.PlaneId });
entity.ToTable("FlightsOfTicket");
entity.Property(e => e.IsDirect)
.IsRequired()
.HasDefaultValueSql("((1))");
entity.HasOne(d => d.Flight)
.WithMany(p => p.FlightsOfTickets)
.HasForeignKey(d => d.FlightId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_FlightsOfTicket_Flight");
entity.HasOne(d => d.Plane)
.WithMany(p => p.FlightsOfTickets)
.HasForeignKey(d => d.PlaneId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_FlightsOfTicket_Plane");
entity.HasOne(d => d.Ticket)
.WithMany(p => p.FlightsOfTickets)
.HasForeignKey(d => d.TicketId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_FlightsOfTicket_Ticket");
});
I know that entity.HasKey(e => new { e.TicketId, e.FlightId, e.PlaneId }) creates a composite key, but at runtime I got this exception:
which means, as far as I know, that it's not creating the composite primary key.
I've tried to create key in different places, tried to re-scaffold model and nothing - it keeps not working for 6 hours now

Entity Framework generate wrong query in many to many relationship database-first

i have relation ship across 6 tables:
associative model:
public class Product
{
public int? GameId { get; set; }
public virtual Game Game { get; set; }
public int? PlatformId { get; set; }
public virtual Platform Platform { get; set; }
public int? ManufactureId { get; set; }
public virtual Manufacture Manufacture { get; set; }
public int? LocalizationId { get; set; }
public virtual Localization Localization { get; set; }
public int? GenreId { get; set; }
public virtual Genre Genre { get; set; }
public int? RegionrestrictId { get; set; }
public virtual Country RegionRestrict { get; set; }
}
main related table:
public class Game
{
public int Id { get; set; }
public string Titleofgame { get; set; }
public string Description { get; set; }
public DateTime DateRelese { get; set; }
public virtual List<Manufacture> Manufactures { get; set; } = new List<Manufacture>();
public List<Product> Products { get; set; } = new List<Product>();
public int? Idseriesofgame { get; set; }
public Serie Series { get; set; }
public int? Idpublication { get; set; }
public Publication Publication { get; set; }
public virtual List<Platform> Platforms { get; set; } = new List<Platform>();
public virtual List<Localization> Localizations { get; set; } = new List<Localization>();
public virtual List<Genre> Genres { get; set; } = new List<Genre>();
public virtual List<Country> RegionRestricts { get; set; } = new List<Country>();
}
and one of the tables which related with "Game"(rest tables are the same)
public class Localization
{
public int Id { get; set; }
[Display(Name = "Язык")]
public string Titleoflocalization { get; set; }
public virtual List<Game> Games { get; set; } = new List<Game>();
public List<Product> Products { get; set; } = new List<Product>();
}
Fluent Api configuration:
modelBuilder
.Entity<Game>()
.HasMany(c => c.Localizations)
.WithMany(s => s.Games)
.UsingEntity<Product>(
j =>
j.HasOne(pt => pt.Localization)
.WithMany(t => t.Products)
.HasForeignKey(pt => pt.LocalizationId),
j =>
j.HasOne(pt => pt.Game)
.WithMany(p => p.Products)
.HasForeignKey(pt => pt.GameId),
j =>
{
j.HasKey(t => new { t.GameId, t.ManufactureId, t.GenreId, t.PlatformId, t.RegionrestrictId, t.LocalizationId });
j.ToTable("Products");
}
);
modelBuilder
.Entity<Game>()
.HasMany(c => c.Platforms)
.WithMany(s => s.Games)
.UsingEntity<Product>(
j =>
j.HasOne(pt => pt.Platform)
.WithMany(t => t.Products)
.HasForeignKey(pt => pt.PlatformId),
j =>
j.HasOne(pt => pt.Game)
.WithMany(p => p.Products)
.HasForeignKey(pt => pt.GameId),
j =>
{
j.HasKey(t => new { t.GameId, t.ManufactureId, t.GenreId, t.PlatformId, t.RegionrestrictId, t.LocalizationId });
j.ToTable("Products");
}
);
modelBuilder
.Entity<Game>()
.HasMany(c => c.Genres)
.WithMany(s => s.Games)
.UsingEntity<Product>(
j =>
j.HasOne(pt => pt.Genre)
.WithMany(t => t.Products)
.HasForeignKey(pt => pt.GenreId),
j =>
j.HasOne(pt => pt.Game)
.WithMany(p => p.Products)
.HasForeignKey(pt => pt.GameId),
j =>
{
j.HasKey(t => new { t.GameId, t.ManufactureId, t.GenreId, t.PlatformId, t.RegionrestrictId, t.LocalizationId });
j.ToTable("Products");
}
);
modelBuilder
.Entity<Game>()
.HasMany(c => c.RegionRestricts)
.WithMany(s => s.Games)
.UsingEntity<Product>(
j =>
j.HasOne(pt => pt.RegionRestrict)
.WithMany(t => t.Products)
.HasForeignKey(pt => pt.RegionrestrictId),
j =>
j.HasOne(pt => pt.Game)
.WithMany(p => p.Products)
.HasForeignKey(pt => pt.GameId),
j =>
{
j.HasKey(t => new { t.GameId, t.ManufactureId, t.GenreId, t.PlatformId, t.RegionrestrictId , t.LocalizationId});
j.ToTable("Products");
}
);
modelBuilder.Entity<Game>()
.HasOne(a => a.Series)
.WithMany(a => a.Games)
.HasForeignKey(c => c.Idseriesofgame);
modelBuilder
.Entity<Game>()
.HasMany(c => c.Manufactures)
.WithMany(s => s.Games)
.UsingEntity<Product>(
j =>
j.HasOne(pt => pt.Manufacture)
.WithMany(t => t.Products)
.HasForeignKey(pt => pt.ManufactureId),
j =>
j.HasOne(pt => pt.Game)
.WithMany(p => p.Products)
.HasForeignKey(pt => pt.GameId).OnDelete(DeleteBehavior.Cascade),
j =>
{
j.HasKey(t => new { t.GameId, t.ManufactureId, t.GenreId, t.PlatformId, t.RegionrestrictId });
j.ToTable("Products");
}
);
modelBuilder.Entity<Game>().HasMany(d => d.Products).WithOne(d => d.Game).HasForeignKey(d => d.GameId).OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Product>()
.HasOne(bc => bc.Game)
.WithMany(b => b.Products)
.HasForeignKey(bc => bc.GameId);
modelBuilder.Entity<Product>()
.HasOne(bc => bc.RegionRestrict)
.WithMany(b => b.Products)
.HasForeignKey(bc => bc.RegionrestrictId);
modelBuilder.Entity<Product>()
.HasOne(bc => bc.Genre)
.WithMany(b => b.Products)
.HasForeignKey(bc => bc.GenreId);
modelBuilder.Entity<Product>()
.HasOne(bc => bc.Localization)
.WithMany(b => b.Products)
.HasForeignKey(bc => bc.LocalizationId);
modelBuilder.Entity<Product>()
.HasOne(bc => bc.Manufacture)
.WithMany(b => b.Products)
.HasForeignKey(bc => bc.ManufactureId);
modelBuilder.Entity<Product>()
.HasOne(bc => bc.Platform)
.WithMany(b => b.Products)
.HasForeignKey(bc => bc.PlatformId);
modelBuilder.Entity<Product>()
.HasKey(bc => bc.GameId );
modelBuilder.Entity<Game>().HasKey(p => p.Id);
modelBuilder.Entity<Genre>().HasKey(p => p.Id);
modelBuilder.Entity<Localization>().HasKey(p => p.Id);
modelBuilder.Entity<Manufacture>().HasKey(p => p.Id);
modelBuilder.Entity<Platform>().HasKey(p => p.Id);
and when i'm trying to remove for example genre by condition:
Product product = new Product() { GameId = 1, GenreId =1};
_context.Entry(product).State = EntityState.Deleted;
var game = publication.Game;
game.Products.Remove(product);
_context.SaveChanges();;
(product with genreid==1 and gameid==1 only one):
i'm getting exception:
and i notice a query, which entity framework genereted:
bug: 20.08.2021 00:25:51.250 RelationalEventId.CommandExecuting[20100] (Microsoft.EntityFrameworkCore.Database.Command)
Executing DbCommand [Parameters=[#p0='1'], CommandType='Text', CommandTimeout='30']
DELETE FROM `Products`
WHERE `gameid` = #p0;
SELECT ROW_COUNT();
info: 20.08.2021 00:25:51.253 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (2ms) [Parameters=[#p0='1'], CommandType='Text', CommandTimeout='30']
DELETE FROM `Products`
WHERE `gameid` = #p0;
SELECT ROW_COUNT();
By the way, when i try to add- all is good.I dont know what i'm doing wrong. Please, help me.

Not able to create user defined tables automatically in Code First Approach using PostgreSql

I am trying to create the tables using code first approach with postgresql database. My DB context is below.While doing migration i am getting the below error.
Unable to determine the relationship represented by navigation
property 'AspNetUser.Projects' of type 'ICollection'. Either
manually configure the relationship, or ignore this property using the
'[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in
'OnModelCreating'.
public class TaskPlannerDbContext : DbContext
{
public DbSet<Project> Projects { get; set; }
public DbSet<Story> Stories { get; set; }
public DbSet<Epic> Epics { get; set; }
public DbSet<Favourite> Favourites { get; set; }
public DbSet<Priority> Priorities { get; set; }
public DbSet<ProjectPermission> ProjectPermission { get; set; }
public DbSet<Theme> Themes { get; set; }
public TaskPlannerDbContext(DbContextOptions<TaskPlannerDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Project>(entity =>
{
entity.HasKey(e => e.ProjectId);
entity.HasOne(d => d.AspNetUser)
.WithMany(p => p.Projects)
.HasForeignKey(d => d.CreatedBy)
.HasForeignKey(a => a.Owner)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_ProjectCreatedBy");
});
builder.Entity<Story>(entity =>
{
entity.HasKey(e => e.StoryId);
entity.HasOne(d => d.AspNetUser)
.WithMany(p => p.Stories)
.HasForeignKey(d => d.CreatedBy)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_StoryCreatedBy");
entity.HasOne(d => d.Project)
.WithMany(p => p.Stories)
.HasForeignKey(d => d.ProjectId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_StoryProjectId");
entity.HasOne(d => d.Epic)
.WithMany(p => p.Stories)
.HasForeignKey(d => d.EpicId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_StoryEpicId");
entity.HasOne(d => d.Theme)
.WithMany(p => p.Stories)
.HasForeignKey(d => d.ThemeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_StoryThemeId");
entity.HasOne(d => d.Priority)
.WithMany(p => p.Stories)
.HasForeignKey(d => d.PriorityId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_StoryPriorityId");
});
builder.Entity<Epic>(entity =>
{
entity.HasKey(e => e.EpicId);
entity.HasOne(d => d.AspNetUser)
.WithMany(p => p.Epics)
.HasForeignKey(d => d.CreatedBy)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_EpicCreatedBy");
entity.HasOne(d => d.Project)
.WithMany(p => p.Epics)
.HasForeignKey(d => d.ProjectId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_EpicProjectId");
});
builder.Entity<Favourite>(entity =>
{
entity.HasKey(e => e.FavouriteId);
entity.HasOne(d => d.Project)
.WithMany(p => p.Favourites)
.HasForeignKey(d => d.ProjectId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_FavouriteProjectId");
});
builder.Entity<Priority>(entity =>
{
entity.HasKey(e => e.PriorityId);
entity.HasOne(d => d.AspNetUser)
.WithMany(p => p.Priorities)
.HasForeignKey(d => d.CreatedBy)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_PriorityCreatedBy");
});
builder.Entity<ProjectPermission>(entity =>
{
entity.HasKey(e => e.PermissionId);
entity.HasOne(d => d.Project)
.WithMany(p => p.ProjectPermissions)
.HasForeignKey(d => d.ProjectId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_ProjectPermissionProjectId");
});
builder.Entity<Theme>(entity =>
{
entity.HasKey(e => e.ThemeId);
entity.HasOne(d => d.AspNetUser)
.WithMany(p => p.Themes)
.HasForeignKey(d => d.CreatedBy)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_ThemesCreatedBy");
entity.HasOne(d => d.Project)
.WithMany(p => p.Themes)
.HasForeignKey(d => d.ProjectId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_ThemesProjectId");
});
}
}

The EntitySet 'AspNetRoles' with schema 'dbo' and table 'AspNetRoles' was already defined. Each EntitySet must refer to a unique schema and table

error in migrations :
PM> enable-migrations Checking if the context targets an existing
database...
System.Data.Entity.ModelConfiguration.ModelValidationException: One or
more validation errors were detected during model generation:
AspNetRoles: Name: The EntitySet 'AspNetRoles' with schema 'dbo' and
table 'AspNetRoles' was already defined. Each EntitySet must refer to
a unique schema and table.
at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate() at
System.Data.Entity.DbModelBuilder.Build(DbProviderManifest
providerManifest, DbProviderInfo providerInfo) at
System.Data.Entity.DbModelBuilder.Build(DbConnection
providerConnection) at
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext
internalContext) at
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps()
at System.Data.Entity.Database.Exists() at
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext1.IsIdentityV1Schema(DbContext
db) at
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext1..ctor(String
nameOrConnectionString, Boolean throwIfV1Schema) at
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext1..ctor(String
nameOrConnectionString) at Apk.Model.ApkEntities..ctor() in
c:\Users\Administrator\Documents\Visual Studio
2013\Projects\Apk\Apk.Data\ApkEntities.cs:line 10
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance() at
System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type
contextType, DbProviderInfo modelProviderInfo, AppConfig config,
DbConnectionInfo connectionInfo, Func`1 resolver) at
System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
configuration, DbContext usersContext, DatabaseExistenceState
existenceState) at
System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
configuration) at
System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration
migrationsConfiguration) at
System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate
callBackDelegate) at
System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
runner) at
System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String
language, String rootNamespace) at
System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at
System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
command) One or more validation errors were detected during model
generation:
AspNetRoles: Name: The EntitySet 'AspNetRoles' with schema 'dbo' and
table 'AspNetRoles' was already defined. Each EntitySet must refer to
a unique schema and table.
Why does this error occur?
I need to change in IdentityRole and IdentityUser.
public class ApkEntities : IdentityDbContext<ApplicationUser>
{
public ApkEntities ()
: base("ApkEntities")
{
}
public virtual void Commit()
{
base.SaveChanges();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Configurations.Add(new AspNetRoleConfiguration());
modelBuilder.Configurations.Add(new AspNetUserConfiguration());
}
}
public class AspNetRoleConfiguration : EntityTypeConfiguration<ApplicationRole>
{
public AspNetRoleConfiguration(string schema = "dbo")
{
ToTable(schema + ".AspNetRoles");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("Id").IsRequired().HasMaxLength(128).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Name).HasColumnName("Name").IsRequired().HasMaxLength(256);
Property(x => x.NameFa).HasColumnName("NameFa").IsRequired().HasMaxLength(50);
Property(x => x.Description).HasColumnName("Description").IsOptional().HasMaxLength(250);
Property(x => x.IsActivated).HasColumnName("IsActivated").IsRequired();
}
}
public class AspNetUserConfiguration : EntityTypeConfiguration<ApplicationUser>
{
public AspNetUserConfiguration(string schema = "dbo")
{
ToTable(schema + ".AspNetUsers");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("Id").IsRequired().HasMaxLength(128).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Email).HasColumnName("Email").IsOptional().HasMaxLength(256);
Property(x => x.PhoneNumberConfirmed).HasColumnName("PhoneNumberConfirmed").IsOptional();
Property(x => x.FirstName).HasColumnName("FirstName").IsOptional();
Property(x => x.LastName).HasColumnName("LastName").IsOptional();
Property(x => x.DateCreated).HasColumnName("DateCreated").IsRequired();
Property(x => x.PasswordHash).HasColumnName("PasswordHash").IsOptional();
Property(x => x.SecurityStamp).HasColumnName("SecurityStamp").IsOptional();
Property(x => x.UserName).HasColumnName("UserName").IsRequired().HasMaxLength(256);
}
}
public class ApplicationRole : IdentityRole
{
public string Description { get; set; }
public string NameFa { get; set; }
public bool IsActivated { get; set; }
}
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
DateCreated = DateTime.Now;
LF_FavoraiteTeam = new Collection<LF_FavoraiteTeam>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? LastLoginTime { get; set; }
public bool? IsActivated { get; set; }
public virtual ICollection<LF_FavoraiteTeam> LF_FavoraiteTeam { get; set; }
}
Try defining your ApplicationUser and ApplicationRole DbSets explicitly in your ApkEntities context and remove the properties which are already in the IdentityRole and IdentityUser objects. The are already defined by inheriting from the IdentityDbContext.

Code First Entity Framework adds an underscore to a primary key column name

I have a fluent mapping of a domain class that defines the names for each column including the primary key which is made up of two columns, NotificationId and IdentityId. These are also foreign keys that point at Notification.Id and Identity.Id respectively. Whenever I use this mapping as part of a query it generates a sql query with an underscore in between Notification and Id (Notification_Id) that is not mentioned anywhere in my mappings.
I would expect that there might be some convention that says that primary keys or foreign keys should look like that but it seems odd given that I've explicitly told it what the column name for NotificationId is.
Any help would be appreciated.
Added mapping file
public class Notifications_IdentitiesMap : EntityTypeConfiguration<Notifications_Identities>
{
public Notifications_IdentitiesMap()
{
ToTable("Notifications.Notifications_Identities");
HasKey(x => new { x.NotificationId,x.IdentityId });
Property(x => x.IdentityId).HasColumnName("IdentityId").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.NotificationId).HasColumnName("NotificationId").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.SendAttempts).HasColumnName("SendAttempts");
Property(x => x.IsSent).HasColumnName("IsSent");
Property(x => x.LastSendAttempt).HasColumnName("LastSendAttempt");
HasRequired(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
HasRequired(x => x.Identity).WithMany().HasForeignKey(x => x.IdentityId);
}
}
public class Notifications_Identities
{
public Notifications_Identities()
{
}
public Notifications_Identities(Notification notification, int identityId)
{
Notification = notification;
IdentityId = identityId;
}
public virtual int IdentityId { get; set; }
public virtual int NotificationId { get; set; }
public virtual int SendAttempts { get; set; }
public virtual DateTime? LastSendAttempt { get; set; }
public virtual Identities.Identity Identity { get; set; }
public virtual Notification Notification { get; set; }
public bool IsSent { get; set; }
}
public class NotificationMap:EntityTypeConfiguration<Notification>
{
public NotificationMap()
{
ToTable("Notifications.Notifications");
Property(x => x.Id).HasColumnName("Id");
Property(x => x.Subject).HasColumnName("Subject").HasMaxLength(255);
Property(x => x.Message).HasColumnName("Message");
Property(x => x.TypeId).HasColumnName("TypeId");
Property(x => x.DateCreated).HasColumnName("DateCreated");
Property(x => x.CreatorIdentityId).HasColumnName("CreatorIdentityId");
HasRequired(x => x.Creator).WithMany().HasForeignKey(x => x.CreatorIdentityId);
}
}
public class IdentityMap : EntityTypeConfiguration<RM.Domain.Identities.Identity>
{
public IdentityMap()
{
Property(x => x.Id).HasColumnName("IDENTITYID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.FirstName).HasColumnName("firstname");
Property(x => x.Surname).HasColumnName("surname");
Property(x => x.Username).HasColumnName("username");
Property(x => x.IsGroup).HasColumnName("is_group");
Property(x => x.EmailAddress).HasColumnName("email");
Property(x => x.ActiveDirectoryId).HasColumnName("ActiveDirectoryId");
Property(x => x.IsLive).HasColumnName("is_active");
ToTable("dbo.rm_tbl_IDENTITY_Identities");
}
}
I made a stupid mistake, found the answer in Entity Framework 4.1 Code First Foreign Key Id's
I added the following:
public virtual ICollection<Notifications_Identities> Identities { get; set; }
to the Notification entity and didn't map it
The fix was to change
HasRequired(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
to
HasRequired(x => x.Notification).WithMany(x=>x.Identities).HasForeignKey(x => x.NotificationId);