I have my application configured to use a SQLRoleManager. I simply created the database, configured the web.config, and let the application create and populate the database tables.
I would like an admin view to preform some simple operations such as add and remove users. Thus, I have created an entity framework data context using the scaffolding wizard and directed it to build around the tables only. (did not check views and stored procedures).
The next thing i wished to do was to then scaffold the controller and view and eventual the model for this data. When I right click controllers I select the add controller with views using entity framework. I fill out the appropriate information selecting an empty class for the model.
I receive the following error which indicates the data is missing keys yet they are in fact defined on the database and in the entity model. Any thoughts as to where i am going wrong here? Do I need to pre build the model? I was hoping to have visual studio create these automatically.
EDIT
Again, the tables all have primary and foreign keys. I can confirm this from Sql Management Studio as well as the .edmx diagram. The bellow code was auto generated. Do i need to add keys?
Context.edmx
UserRole_Context.tt > aspnet_Users.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IDM.DAL
{
using System;
using System.Collections.Generic;
public partial class aspnet_Users
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public aspnet_Users()
{
this.aspnet_PersonalizationPerUser = new HashSet<aspnet_PersonalizationPerUser>();
this.aspnet_Roles = new HashSet<aspnet_Roles>();
}
public System.Guid ApplicationId { get; set; }
public System.Guid UserId { get; set; }
public string UserName { get; set; }
public string LoweredUserName { get; set; }
public string MobileAlias { get; set; }
public bool IsAnonymous { get; set; }
public System.DateTime LastActivityDate { get; set; }
public virtual aspnet_Applications aspnet_Applications { get; set; }
public virtual aspnet_Membership aspnet_Membership { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<aspnet_PersonalizationPerUser> aspnet_PersonalizationPerUser { get; set; }
public virtual aspnet_Profile aspnet_Profile { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<aspnet_Roles> aspnet_Roles { get; set; }
}
}
UserRole_Context.Context.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IDM.DAL
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class IDMEntities : DbContext
{
public IDMEntities()
: base("name=IDMEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<aspnet_Applications> aspnet_Applications { get; set; }
public virtual DbSet<aspnet_Membership> aspnet_Membership { get; set; }
public virtual DbSet<aspnet_Paths> aspnet_Paths { get; set; }
public virtual DbSet<aspnet_PersonalizationAllUsers> aspnet_PersonalizationAllUsers { get; set; }
public virtual DbSet<aspnet_PersonalizationPerUser> aspnet_PersonalizationPerUser { get; set; }
public virtual DbSet<aspnet_Profile> aspnet_Profile { get; set; }
public virtual DbSet<aspnet_Roles> aspnet_Roles { get; set; }
public virtual DbSet<aspnet_SchemaVersions> aspnet_SchemaVersions { get; set; }
public virtual DbSet<aspnet_Users> aspnet_Users { get; set; }
public virtual DbSet<aspnet_WebEvent_Events> aspnet_WebEvent_Events { get; set; }
}
}
Connection String
<add name="IDMEntities" connectionString="metadata=res://*/DAL.UserRole_Context.csdl|res://*/DAL.UserRole_Context.ssdl|res://*/DAL.UserRole_Context.msl;provider=System.Data.SqlClient;provider connection string="data source=*******;initial catalog=IDM;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
Related
I am trying to build database on MySQL server in .Net Framework 4.5.2 using Entity Framework 6.2.0. For connection with MySql I use nugets MySQL.Data, MySQL.EntityFramework, MySQL.Web all at version 8.0.16. Connection works fine.
The problem is with code first approach and generating behaviour on foreign key constraints. I want to have On Delete Set Null behaviour but simply cannot get it in generated database. All I have for now is On Delete Restrict or Cascade. Is this a problem with MySQL, Connector, EF6?
I tried to set relation with this behaviour with fluent api. I have read that setting property with fk constraint nullable should do the trick. I also have disabled On Delete Cascade by addding .WillCascadeOnDelete(false).
Here are two entities that I want to connect with simple One to Many relation:
public class Company
{
public long Id { get; set; }
public string Name { get; set; }
public long? AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public long Id { get; set; }
public string Street { get; set; }
public string Number { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public virtual ICollection<Company> Company { get; set; }
}
And the DbContext:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
class OwrContext : DbContext
{
public OwrContext() : base(nameof(OwrContext))
{
DbConfiguration.SetConfiguration(new MySqlEFConfiguration());
}
public virtual DbSet<Address> Address { get; set; }
public virtual DbSet<Company> Company { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Company>()
.HasOptional(c => c.Address)
.WithMany(a => a.Company)
.HasForeignKey(c=>c.AddressId)
.WillCascadeOnDelete(false);
}
}
I feal that there is a problem with MySQL connector, but maybe there is something else I could try?
I have an existing application that I am re-writing as .NET Core API with a ReactJS front-end. I am still in the API end, and I've run into a problem.
CODE
I have a BbUser.cs entity class with the following code:
public class BbUser : IdentityUser
{
public int Points { get; set; } = 0;
public string DisplayUsername { get; set; }
}
And I also have an Artist.cs entity class:
public class Artist
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string FirstName { get; set; }
[MaxLength(50)]
public string LastName { get; set; }
[MaxLength(100)]
public string UrlFriendly { get; set; }
public string ImageUrl { get; set; }
public bool IsVerified { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public ICollection<Lyric> Lyrics { get; set; } = new List<Lyric>();
public string UserId { get; set; }
public BbUser User { get; set; }
}
I need a one-to-many relationship between BbUser and Artist. One user can submit many artists and lyrics ...etc. Simple stuff really.
PROBLEM
The application builds fine, but when I attempt to run it by hitting a controller that requires access to the Database, I get the following error:
The entity type 'IdentityUserLogin' requires a primary key to be defined.
I had this issues with regular EF Code First (not Core) and the fix for that, does not work here.
This model worked for me(compiled, and no exceptions at runtime) if I used next code in the DbContext class:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<BbUser>(b => b.ToTable("AspNetUsers"));
base.OnModelCreating(builder);
}
Without calling base.OnModelCreating(builder) I get the same error, because in this case context isn't applying the Identity related schema.
UPDATE:
Everything works fine for me as you can see from the screenshot below:
I have one more idea why you can have such an error. Did your BbContext inherit from DbContext class or IdentityDbContext<IdentityUser>? Because I got the same error that was on your screenshot if I used usual DbContext class.
In order to Idenity tables work fine you should use IdentityDbContext<IdentityUser>. Below the whole code for my working DbContext class
public class BbContext :IdentityDbContext<IdentityUser>
{
public BbContext(DbContextOptions options):base(options)
{
Database.EnsureCreated();
}
public DbSet<Artist> Artists { get; set; }
public DbSet<Lyric> Lyrics { get; set; }
public DbSet<Heart> Hearts { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<BbUser>(b => b.ToTable("AspNetUsers"));
builder.Entity<Heart>().HasKey(h => new {h.UserId, h.LyricId});
base.OnModelCreating(builder);
}
}
Please do try declaring a Guid property named Id, with both Get and Set on the IdentityUserLogin entity.
Another option is to declare a property and decorate it with [Key] attribute
I have this error
Invalid object name 'dbo.Vacancies'
But I have Model for Vacancies.
Here it is:
public partial class Vacancy
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Vacancy()
{
this.Interwiers = new HashSet<Interwier>();
this.InvitationMails = new HashSet<InvitationMail>();
}
[Key]
public int Vacancy_Id { get; set; }
[Display(Name="Вакансия")]
public string VacancyName { get; set; }
public Nullable<int> CompanyID { get; set; }
public virtual Company Company { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Interwier> Interwiers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<InvitationMail> InvitationMails { get; set; }
}
}
Also I have table Vacancy.
This code I have in IdentityModels:
public System.Data.Entity.DbSet<SmartSolutions.Models.Vacancy> Vacancies { get; set; }
Here is code of View where I try to show data from table.
// GET: VacanciesAll
public ActionResult Index()
{
var vacancies = db.Vacancies.Include(v => v.Company);
return View(vacancies.ToList());
}
Here is the Table:
Here is the table in EF
Why am I getting an error?
Check if the Table exists in your Sql Database. Chances are it is not there in your Database, hence, the error.
If the table exists, make sure you are mapping your EF table to the correct table name in DbContext.
It could be loooking at the wrong database.
The DbContext class should match the name in the connection string.
Make sure your connection string "name" property is correct.
Example: PortalEntities DbContext should match PortalEntities in connectionStrings.
public class PortalEntities : DbContext
{
public DbSet<Delegate> Delegates { get; set; }
public DbSet<Status> Statuses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<PortalEntities>(null);
base.OnModelCreating(modelBuilder);
}
}
<connectionStrings>
<add name="PortalEntities" connectionString="Data Source=serverName;Integrated Security=true;Initial Catalog=dbName;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Please check the EF Layers [ SSDL - CSDL - MSL ]
this is conflict between your EF layers and database engine
I am trying to figure out if my DBContext is set right. The Web Application I am trying to do is using ASP.NET 5, MVC6 and EF7.
It is connected to a DB that contains 3 tables (Comment, Review, Film). This is my model
WebDbModel.cs
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace WebExample.Models
{
public partial class Comment : IdentityUser
{
public string CommentId { get; set; }
public string ReviewId { get; set; }
public string Author { get; set; }
public System.DateTime Created { get; set; }
}
public partial class Review : IdentityUser
{
public string ReviewId { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string Creator { get; set; }
public string Status { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
}
public partial class Film : IdentityUser
{
public string ReviewId { get; set; }
public string FilmID { get; set; }
public string CommentId { get; set; }
public Nullable<int> CommentCount { get; set; }
public string FilmName { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual Review Review { get; set; }
}
}
Then, I have a class named
RegistrationDbContext.cs
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
namespace WebExample.Models
{
public class ApplicationUser : IdentityUser
{
}
public class RegistrationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
// Registration of the DB tables we are mapping.
public DbSet<Comment> Comments { get; set; }
public DbSet<Review> Reviews { get; set; }
public DbSet<Film> Films { get; set; }
}
}
I am wondering from here what is the use of public class ApplicationUser : IdentityUser
I am not sure if I should leave it there... If I remove it, then in my Startup.cs, the following code will complain...
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<RegistrationDbContext>()
.AddDefaultTokenProviders();
So I don't know to what replace it given the fact I have Comment, Review and Film models...
So my question is... I guess I can delete the ApplicationUser class (auto generated when I created my solution) since this is not part of my model at all but... what should I put instead?
Not too sure if my question is right though, so apologies in advance! This seemed to be changed a lot compared to MVC5, EF6 and I couldn't fine too much documentation around IdentityDbContext
Also... am I missing something else in the RegistrationDbContext.cs class? The only extra thing I added was the registration of the tables... the rest came in the class by default.
Thanks!
There are a couple of issues here.
Firstly, IdentityUser is the representation of a logged-in user to your site, and is by default represented by the AspNetUsers table in the database, and stores all the usual stuff like email address, password, etc.
The provided ApplicationUser subclass is there in case you want to extend that in any way. Say for example you want to store the date of birth of your users:
public class ApplicationUser : IdentityUser
{
public DateTime DateOfBirth { get; set; }
}
That will tack on a DateOfBirth column to the AspNetUsers table.
In your case, if you don't want to extend the default user table in any way, you can just delete the ApplicationUser class and replace all references to it in your code to IdentityUser. For example:
// Add Identity services to the services container.
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<RegistrationDbContext>()
.AddDefaultTokenProviders();
Secondly, your models should not be inheriting from IdentityUser. That will just add all the fields from the AspNetUsers table to every model, which doesn't make sense, so remove : IdentityUser from your models.
This is my first day I've spent exploring ASP.NET MVC 4. Specifically I'm using the Web API and obviously this issue is actually an MS SQL issue. I'm running EF migrations PM> Update-Database to get this error, but have seen it when first creating the models. My models are:
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public int MakeId { get; set; }
public virtual Make Make { get; set; }
public int ModelId { get; set; }
public virtual Model Model { get; set; }
}
public class Make
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Model> Models { get; set; }
}
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public int MakeId { get; set; }
public virtual Make Make { get; set; }
}
The DB context is:
public class CarsContext : DbContext
{
public CarsContext() : base("name=CarsContext") { }
public DbSet<Car> Cars { get; set; }
public DbSet<Make> Makes { get; set; }
public DbSet<Model> Models { get; set; }
}
}
Would appreciate any help. My background is 5/6 solid of PHP and MySQL, so this is a steep learning curve.
Thanks.
Luke McGregor is correct. In addition to the way you fixed this you can override the default mapping that entity framework is giving you so that it doesn't cascade delete. In you CarsContext class you can override the OnModelCreating() method and specify your own mappings using fluent. This overrides what EF is trying to do by default. So you can do something like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.HasOptional(x => x.Model)
.WithMany(y => y.Cars) //Add this property to model to make mapping work
.WillCascadeOnDelete(false);
}
This will still work with automatic migrations.
Hope that helps.