Not able to enable migrations through Nuget Package Manager - entity-framework

I am trying enable-migrations in console but getting this error.
I am getting this error, please help anyone.
The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.
This is my program.cs file
public class Employee
{
public int EmpID { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
}
public class BlogDbContext : DbContext
{
public Dbset<Employee> Employees { get; set; }
}
class Program
{
static void Main(string[] args)
{
}
}

Related

How do I fix this SQLite error: SQLite Error 1: 'table "StudentCourses" already exists'

I'm creating a CRUD project in asp.net entity framework, and from my understanding, in order to see the data on the HTML page I have to scaffold the pages. For example I have two entity models Student and Major
This is the Student entity
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Major")]
public int? MajorId { get; set; }
public Major Major { get; set; }
[ForeignKey("Advisor")]
public int AdvisorId { get; set; }
public Advisor Advisor { get; set; }
public ICollection<StudentCourses>? StudentCourses { get; set; }
}
This is the Major entity
public class Major
{
public int MajorId { get; set; }
public string MajorName { get; set; }
public ICollection<Student> Students { get; set; }
public ICollection<Advisor> Advisors { get; set; }
public ICollection<MajorCourse> MajorCourses { get; set; }
}
If I want to see the Student data I have to create a Students folder and add a new Scaffolding along with a DbContext like your_namespace.Data.StudentContext. I would also have to follow the same steps for the Major entity but am I correct to use another DbContext? For example: your_namespace.Data.MajorContext. This is what I have done but when I try to make migrations and update the database in the your_namespace.Data.MajorContext, I get an error that reads SQLite Error 1: 'table "StudentCourses" already exists'.`
How do I fix this error?
I should also add the Context classes:
This is the StudentContext class:
public class AdvismentContext : DbContext
{
public AdvismentContext(DbContextOptions<AdvismentContext> options)
: base(options)
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Major> Majors { get; set; }
public DbSet<Advisor> Advisors { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<MajorCourse> MajorCourses { get; set; }
public DbSet <StudentCourses> StudentCourses{ get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.ToTable("Students");
modelBuilder.Entity<Major>()
.ToTable("Majors");
modelBuilder.Entity<Advisor>()
.ToTable("Advisors");
modelBuilder.Entity<Course>()
.ToTable("Courses");
//modelBuilder.Entity<MajorCourse>()
// .ToTable("MajorCourse");
//.HasKey(mc => new { mc.MajorId, mc.CourseId });
}
And this is the MajorContext class:
public class MajorContext : DbContext
{
public MajorContext (DbContextOptions<MajorContext> options)
: base(options)
{
}
public DbSet<Advisment.Models.Major> Major { get; set; } = default!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Major>()
.ToTable("Major");
//modelBuilder.Entity<MajorCourse>() This is commented out because I was getting the same error that the table already exists.
// .ToTable("MajorCourse");
}
}
What am I doing wrong?

I can't create a simple dataBase in EntityFramework Core

I'm a realy newbie in EntityFramework and Core.
I want to create a simple DataBase in EntityFramework Core 2.0. The project is a ConsoleApplication that I included it a Microsoft.AspNetCore.All by Nuget package. This is a code:
namespace TestEF
{
class Program
{
static void Main(string[] args)
{
string connStr = "Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";
var db = new SchoolContext(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connStr).Options);
db.Students.Add(
new Student()
{
LastName = "Miranda",
EnrollmentDate = DateTime.Now,
FirstMidName = "Guillermo"
});
db.SaveChanges();
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
}
}
I'm loggin into a intranet as username "gmiranda". When I run the project I get the following message error:
System.Data.SqlClient.SqlException occurred
HResult=0x80131904
Message=Cannot open database "SchoolDataBase" requested by the login. The login failed.
Login failed for user 'domain\gmiranda'.
What is I doing wrong ?
Thanks !
You should try this code:
class Program
{
static void Main(string[] args)
{
string connStr = "Data Source=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";
var db = new SchoolContext();
db.Students.Add(
new Student()
{
LastName = "Miranda",
EnrollmentDate = DateTime.Now,
FirstMidName = "Guillermo"
});
db.SaveChanges();
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
public class SchoolContext : DbContext
{
public SchoolContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true");
}
public DbSet<Student> Students { get; set; }
}
Then open Package Manager Console and use command Add-Migration FirstMigrarion.
Its add migration to your database with name FirsMigration.
Then use command Update-Database.
Then run your program.
Try use this tutorial: https://learn.microsoft.com/en-us/ef/core/get-started/full-dotnet/new-db

NullReferenceException on join with Postgres EF Provider

I have a postgres database and using asp.net core mvc (+ ef). The database is created correctly. I have two tables 'Module' and 'ModuleMenu'. I want to get all the menu's for a given module but I keep on failing to create the linq query.
Situation
Model: Module.cs
namespace project.Model
{
public class Module
{
[Required]
public string ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
}
}
Model: ModuleMenu.cs
namespace project.Models
{
public class ModuleMenu
{
[Required]
public string ID { get; set; }
public int ModuleID { get; set; }
[Required]
public string Title { get; set; }
[ForeignKey("ModuleID")]
public virtual Module Module { get; set; }
}
}
ApplicationDbContext.cs
namespace project.Data
{
public class ApplicationDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<Module> Modules { get; set; }
public DbSet<ModuleMenu> ModuleMenus { get; set; }
}
}
Query
public List<ModuleMenu> GetModuleMenus(){
var query = from m in _dbContext.ModuleMenus
join mod in _dbContext.Modules on
m.ModuleID equals mod.ID
select m;
return query.ToList();
}
Error
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An exception was thrown attempting to execute the error handler.
System.NullReferenceException: Object reference not set to an instance of an object.
Can anyone help me to correctly create the query?
Is this part correct in your code?
public int ModuleID { get; set; }
It seems that you might have had an error in the type used for the fk.
Below I changed the type to be string rather than int.
public string ModuleID { get; set; }
based on that update, the query could look like this.
public ModuleMenu[] GetModuleMenusForModule(string moduleId)
{
return _dbContext.ModuleMenus.Where(x => x.ModuleID == moduleId).ToArray();
}
I would expect that model to error (ModelID and ID are incompatible types). If that were correct, your code should work. Or simpler:
public List<ModuleMenu> GetModuleMenus()
{
return _dbContext.ModuleMenus.ToList();
}

InvalidOperationException: The entity type 'object' requires a key to be defined

Entity-framework 7.
[Table("Settings")]
public class Setting
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public object DefaultValue { get; set; }
public string Classification { get; set; }
public FacilitySettingOverride FacilitySettingOverride { get; set; }
}
[Table("FacilitySettingOverride")]
public class FacilitySettingOverride
{
[Key]
[ForeignKey("FacilityId")]
public int FacilityId { get; set; }
public object Value { get; set; }
[ForeignKey("SettingId")]
public int SettingId { get; set; }
public virtual ICollection<Setting> Settings { get; set; }
}
[Table("Facilities")]
public class Facility
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<FacilitySettingOverride> FacilitySettingOverrides { get; set; }
}
When run the code
private IEnumerable<FacilitySettingOverride> GetFacilityBandwidthSettings
{
get
{
List<FacilitySettingOverride> settingList;
using (SettingDbContext context = new SettingDbContext())
{
settingList = context.FacilitySettingOverride.ToList();
}
return settingList;
}
}
Then get the exception:
InvalidOperationException: The entity type 'object' requires a key to be defined.
The context is:
public class SettingDbContext : DbContext
{
public DbSet<Setting> Settings { get; set; }
public DbSet<FacilitySettingOverride> FacilitySettingOverride { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=13.53.63.74;Initial Catalog=AAAAA;User ID=sa;password=password);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
However if I change the object to string for Value or DefaultValue in POCO then no exception. But the type in the database is sql_variant. I have to use the type object.
It seems that Data annotations are not yet supported so you will need to use the Fluent API for configuration.
See: https://github.com/aspnet/EntityFramework/issues/1913#issuecomment-86662854

Entity Framework Navigation Property Error

I am getting this error in my .Net MVC 4 web application:
The property 'Username' cannot be configured as a navigation property. The
property must be a valid entity type and the property should have a non-abstract
getter and setter. For collection properties the type must implement
ICollection<T> where T is a valid entity type.
I am very new to Entity Framework and I can't seem to get around this issue. Here is some code:
//DB Context
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(u => u.Roles).WithMany(r => r.Users).Map(x => x.MapLeftKey("Username").MapRightKey("RoleName").ToTable("Users_Roles"));
}
}
//Entity Classes
public class User
{
[Key]
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Comment { get; set; }
public int Level { get; set; }
public string PasswordQuestion { get; set; }
public string PasswordAnswer { get; set; }
public bool IsApproved { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime CreationDate { get; set; }
public bool IsOnLine { get; set; }
public bool IsLockedOut { get; set; }
public DateTime LastLockedOutDate { get; set; }
public int FailedPasswordAttemptCount { get; set; }
public DateTime FailedPasswordAttemptWindowStart { get; set; }
public int FailedPasswordAnswerAttemptCount { get; set; }
public DateTime FailedPasswordAnswerAttemptWindowStart { get; set; }
[InverseProperty("RoleName")]
public virtual ICollection<Role> Roles { get; set; }
public override string ToString()
{
return this.Username;
}
}
public class Role
{
[Key]
public string RoleName { get; set; }
public int Level { get; set; }
[InverseProperty("Username")]
public virtual ICollection<User> Users { get; set; }
public override string ToString()
{
return this.RoleName;
}
}
//Repository
public class EFUsersRepository : IUsersRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<User> Users
{
get { return context.Users; }
}
public User GetUser(string username)
{
return context.Users.Find(username); //THIS IS WHERE THE CRASH OCCURS
}
}
//DB Setup
Table Users, Role and Users_Role. Users_Role is a simple linking table with [username, role] columns both of type varchar.
The database tables columns & types match the two classes above (User,Role).
I inherited this project which was unfinished but I can't get it to run successfully. Any help understanding what the issue is would be helpful. Thanks!
It might be that Entity Framework is updated. Easiest way will be to recreate the DataModel.
Even if the previous programmer did not use Entity Data Mode, you can at least copy the auto generated code such as EFDbContext, Users and Roles classes.
It turns out, after commenting out enough items all day long, the the following lines are what caused this error for me:
[InverseProperty("RoleName")] //In file User.cs (as shown above)
[InverseProperty("UserName")] //in file Role.cs (as shown above)
I am still learning Entity Framework and I don't know why this was the solution, but it stopped the error which I reported above.
I hope that this helps someone else and if anyone wants to help me understand what the issue was in detail, please feel free. I am eager to learn.