There is already an object named'' in the database entity framework - c#

I have a DbContext like this,
public class EPDContext : TrackerContext
{
public EPDContext()
: base("name=DevelopmentApplicationServices")
{
Database.SetInitializer<EPDContext>(new EPDDBInitializer());
this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
}
public DbSet<TaskRevision> TaskRevisions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<TaskRevision>().HasMany(x => x.Models).WithMany().Map(x => x.MapLeftKey("TaskRevisionID").MapRightKey("ModelId").ToTable("TaskRevision2Models"));
}
}
public class EPDDBInitializer : CreateDatabaseIfNotExists<EPDContext>
{
protected override void Seed(EPDContext context)
{
//// My Seeding data goes here
base.Seed(context);
}
}
And my Entity:
[TrackChanges]
public class TaskRevision
{
#region properties
[Key]
public Guid TaskRevisionID { get; set; }
public virtual List<Model> Models { get; set; }
}
and my migration configuration class looks like:
internal sealed class Configuration : DbMigrationsConfiguration<PW.EPD.Data.EPDContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(PW.EPD.Data.EPDContext context)
{
}
}
I got this error "There is already an object named 'TaskRevisions' in the database entity framework." when I execute my application. DB has created successfully and there is no seeding data.
At the same time when I execute the same code after removing the onModelCreating() override method, db has created with seed data.
What I did wrong here, kindly correct me.
Thanks in advance

Related

MAUI 'SQLite Error 1: 'no such table: Players'.'

when i want to add fields in the database it tells me "SQLite Error 1: 'no such table: Players'." but as soon as i look at my database there is a players table. how can i solve this problem?
Here are the files for saving in the DB
GameDbContext
namespace MereTuBois.Data
{
public class GameDbContext : DbContext
{
private readonly IDeviceService _deviceService;
public DbSet<Players> Players { get; set; }
public DbSet<Session> Sessions { get; set; }
public GameDbContext(IDeviceService deviceService)
{
_deviceService = deviceService;
//this.Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string dbPath = Path.Combine(_deviceService?.AppDataDirectory ?? ".", "mereTubois.db3");
optionsBuilder.UseSqlite($"Filename={dbPath}");
}
}
public class HistoryContextFacotry : IDesignTimeDbContextFactory<GameDbContext>
{
public GameDbContext CreateDbContext(string[] args)
{
return new GameDbContext(null);
}
}
}
link to the migration : https://github.com/Waterlok653/MIgration
to solve the problem I have removed the following comment : this.Database.EnsureCreated();

How should I seed data in Entity Framework 6

I've problem with seeding data to database. Eariler I tried way from this tut: Seed Data in EF 6 Code-First
and then the seed method is never called
DBSchool.cs
namespace SchoolTest.DAL
{
public class DBSchool : DbContext
{
public DBSchool() : base("DBSchool")
{
Database.SetInitializer(new Seeder());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Guest> Guests { get; set; }
}
}
Seeder.cs
public class Seeder : DropCreateDatabaseAlways<DBSchool>
{
protected override void Seed(DBSchool context)
{
IList<Guest> GuestList = new List<Guest>();
GuestList.Add(new Guest()
{
Name = "Dexter",
Surname = "Dexter",
Email = "test#test.com"
});
context.Guests.AddRange(GuestList);
context.SaveChanges();
base.Seed(context);
}
}
Guest.cs
public class Guest
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
[Key]
public int GuestId { get; set; }
}
App.config
<appSettings>
<add key="DatabaseInitializerForType SchoolTest.DAL.DBSchool, SchoolTest"
value="SchoolTest.Data.Seeder, SchoolTest" />
</appSettings>
Is there any way to call the Seed() method or just through the Configuration.cs?
Try changing your code like this.
public class DBSchool : DbContext
{
public DBSchool() : base("name=<database-name>")
{
Database.SetInitializer<DBSchool>(new Seeder());
}
// Rest of your implementation
}
Replace <database-name> with the name of your database.
If that didn't work, you can give a Generic Type Parameter to the context class and change your code as follows.
Seeder.cs -> public class Seeder<T> : DropCreateDatabaseAlways<DBSchool>
DBSchool.cs -> Database.SetInitializer<DBSchool>(new Seeder<DBSchool>());
Read more on that here.
If that didn't work either, you can use migrations and seed data using custom sql using Sql().

EF Core Query Custom IdentiyUser

I am still relatively new to EF Core and beforehand I used PetaPoco, so please forgive my ignorance. In my database, I added the following fields to my AspNetUsers table:
Elevated
Deactivated
FirstName
LastName
I then created the following classes following this blog article:
public partial class ApplicationUser : IdentityUser
{
public bool? Deactivated { get; set; }
public bool? Elevated { get; set; }
[StringLength(255)]
public string FirstName { get; set; }
[StringLength(255)]
public string LastName { get; set; }
}
and
public class ApplicationClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
public ApplicationClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
{ }
public override async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
if (!string.IsNullOrWhiteSpace(user.FirstName))
{
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim(ClaimTypes.GivenName, user.FirstName)
});
}
if (!string.IsNullOrWhiteSpace(user.LastName))
{
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim(ClaimTypes.Surname, user.LastName)
});
}
return principal;
}
}
I also setup the AddIdentity and AddScoped methods too in my Startup.cs file.
What I do not understand going forward from this point is how to query the table, returning my custom properties. In my controller, I want to do something like this:
/// <summary>
/// Gets every User.
/// </summary>
/// <returns>HTTP Result</returns>
[HttpGet]
[Route("")]
public async Task<ActionResult<IEnumerable<ApplicationUser>>> GetUsers()
{
var users = await this._context.Users.Select(user => new
{
user.Id,
user.Decativated,
user.Elevated,
user.Email,
user.FirstName,
user.LastName
}).ToListAsync();
return Ok(users);
}
But obviously I can't because the properties don't exist on the Users DbSet.
So long story short, I think that I have everything setup properly but how do I actually query my extended IdentityUser?
EDIT
As requested, the following is my DbContext. I only have a dummy table wired up right now as I was just trying to get the extensions on the AspNetUsers table working first:
public partial class [removed for confidentiality]Context : IdentityDbContext
{
public [removed for confidentiality]Context()
{
}
public [removed for confidentiality]Context(DbContextOptions<[removed for confidentiality]Context> options)
: base(options)
{
}
public virtual DbSet<Foo> Foos { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "[removed for confidentiality]");
modelBuilder.Entity<Foo>(entity =>
{
entity.Property(e => e.FooName).IsUnicode(false);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
You have to specify type parameter(s) for IdentityDbContext. You need to inherit from IdentityDbContext<TUser> class. Without type parameters you are using classes defined in ASP.NET Core Identity. Everything you'd like to change must be reflected in your code.
public partial class [removed for confidentiality]Context : IdentityDbContext<ApplicationUser>
{
public [removed for confidentiality]Context()
{
}
public [removed for confidentiality]Context(DbContextOptions<[removed for confidentiality]Context> options)
: base(options)
{
}
public virtual DbSet<Foo> Foos { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "[removed for confidentiality]");
modelBuilder.Entity<Foo>(entity =>
{
entity.Property(e => e.FooName).IsUnicode(false);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

Entity Framework automatic migrations enabled does not work

I have this db configuration
public class AppDbContext : DbContext
{
public AppDbContext(string connectionStringOrName)
: base(connectionStringOrName)
{
Database.SetInitializer(new AppDbInitializer());
}
public AppDbContext()
: this("name=AppDbContext")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Log> Logs { get; set; }
}
and I have this migration configuration
public class AppDbInitializer : MigrateDatabaseToLatestVersion<AppDbContext,AppDbMigrationConfiguration>
{
}
public class AppDbMigrationConfiguration : DbMigrationsConfiguration<AppDbContext>
{
public AppDbMigrationConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(AppDbContext context)
{
if (context.Users.Any()) return;
AddAdmin(context, "Admin", "admin#test.com");
}
}
And I added another field to Log entity.
Can Entity Framework automatically detect and apply changes?
If Automatic Migrations are enabled, it should auto detect any small changes in the model.
But for larger changes, eg addition of new entity, I have seen to manually apply migration, which you can do with "Add-Migration" and then running "Update-Database"

EF 4.3 code first one-to-one relations

Could anybody tell me what's wrong with this code below, because I'm having problems getting an one-to-one relation working with EF 4.3 code first.
// Problem with EF 4.3 code first, one-to-one relation
// context
// ------------
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<SecondModel>().HasRequired(r => r.FirstModel).WithOptional(r => r.SecondModel).WillCascadeOnDelete(false);
}
// models
// --------
public abstract class MyBaseEntity : // some interfaces
{
// ...
[EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]
public virtual int Id
{
get { return GetPropertyValue<int>("Id"); }
set { SetPropertyValue<int>("Id", value); }
}
// ...
}
public class FirstModel : MyBaseEntity
{
// ...
public int SecondModelID { get; set; }
public virtual SecondModel SecondModel { get; set; }
// ...
}
public class SecondModel : MyBaseEntity
{
// ...
public int FirstModelID
{
get { return GetPropertyValue<int>("FirstModelID"); }
set { SetPropertyValue<int>("FirstModelID", value); }
}
public virtual FirstModel FirstModel { get; set; }
// ...
}
// this code above doesn't seem to work :s
// when removing FirstModelID and removing SecondModelID i'm unable to create the the database
Have been trying all kinds of things, adding foreignkey attributes, (un)commenting some id's, following samples.
Results were always: IDs in database are not correctly or it doesn't create the database.
Thanks in advance.
I dont have EF 4.3 but it is surprising if it is different from EF 4.1 in this regard. I've done it by configuring the model in the fluent API, overriding the ModelBuilder like this inside the DbContext class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<FirstModel>()
.HasRequired(e => e.SecondModel)
.WithRequiredPrincipal()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
And the classes:
public class FirstModel : MyBaseEntity
{
// ...
public virtual SecondModel SecondModel { get; set; }
// ...
}
public class SecondModel : MyBaseEntity
{
// ...
public int Id
{
get { return GetPropertyValue<int>("FirstModelID"); }
set { SetPropertyValue<int>("FirstModelID", value); }
}
// ...
}

Categories