Enable migrations with reference to ApplicationUser identity framework code first - asp.net

I'll create a database with identity framework (code first way) but I've errors when I run code below in the package manager.
PM> Enable-Migrations -ContextTypeName FreeTime.AspMvc.Context.FreeTimeContext -Force
Here are my errors:
IdentityUserLogin: : EntityType IdentityUserLogin has no key defined. Define the key for this EntityType.
IdentityUserRole: : EntityType IdentityUserRole has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet IdentityUserLogins is based on type IdentityUserLogin that has no keys defined.
IdentityUserRoles: EntityType: EntitySet IdentityUserRoles is based on type IdentityUserRole that has no keys defined.
More information:
(Click to see full screen)
In other classes I've made a property type of ApplicationUser named UserId and one of type of string named User for holding witch user has made witch topic. Here you've an example:
public class Topic
{
[Key]
public int TopicId { get; set; }
[ForeignKey("dbo.AspNetUsers.Id")]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
}
Small update: Here is my context file:
public class FreeTimeContext: DbContext
{
public DbSet<Topic> Topics { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
I've also seen that there is a second context file named ApplicationDbContext.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("FreeTimeContext" /* --> this I've edited into my own name */,
throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Big update: In a later state I've tried other things like list below:
First I've tried to enabled the migrations for ApplicationDbContext. Here are the steps I've done.
First I've run this code:
PM> enable-migrations -ContextTypeName FreeTime.AspMvc.Models.ApplicationDbContext -ForceThis is done without errors.
Then I've run this:
PM> add-migration "initAspTables"
Also no problems with this code.
Finaly I've update my database:
PM> Update-Database
Also done with no problems.
Check if the tables are created into the server manager → Check but doesn't contain my own tables. ☹
Conclusion: not really what I will have.
Second thing I've done is inherit FreeTimeContext from ApplicationContext instead of DbContext like code below.public class FreeTimeContext: ApplicationDbContext
{
public DbSet Topics { get; set; }
public FreeTimeContext(): base()
{ }
// other code
}And again to try enable the migrations with this code:
PM> enable-migrations -ContextTypeName FreeTime.AspMvc.Context.FreeTimeContext -Force
but I've this error:
The ForeignKeyAttribute on property UserId on type FreeTime.AspMvc.Models.Topic is not valid. The navigation property dbo.AspNetUsers.Id was not found on the dependent type FreeTime.AspMvc.Models.Topic. The Name value should be a valid navigation property name.More information:(Click to see full screen)Conclusion: didn't work.
Can you help me? I don't know what else I could do to migrate the class ApplicationUser together with my own classes to the database.

Related

I could not connect to database instance created with Entity Framework generated from model

I created a web application and a model. Then I generated a dbcontext class and a database instance. After I built the project, I tried to connect to that database from Server Explorer in Visual Studio, but could not connect.
I tried to test connection but got an error:
This connection cannot be tested because the specified database does not exist or is not visible to the specified user
Whenever I tried to scaffold view or controller I got this error:
Unable to retrieve metadata for ... one or more validation errors were detected during model generation
ModelsTable is based on type TestModel that has no keys defined.
When I created database object in controller class and write query got same error no key defined.
Also made updates on packages and tried again. I think my connection string is correct.
Here is my model.
public class TestModel
{
[Key]
public string ID { get; } = Guid.NewGuid().ToString();
public string AreaName { get; set; }
public bool IsWorking { get; set; }
public string UserName { get; set; }
public DateTimeOffset Time { get; set; }
}
So I could not use scaffolding, Entity Framework and write query.
Here is my dbcontext class.
public class ModelDB : DbContext
{
public ModelDB()
: base("name=ModelDB")
{
}
public DbSet<TestModel> ModelsTable { get; set; }
}
I searched on internet tried founded solutions but did not understand and could not solve. I hope did not ask unnecessary questions. Thanks for your helping.
Are you using Code First? If so I think you need to generate migrations.
In visual studio go to Package Manager Console and run this commands:
Add-Migration "modelClassName"
Update-Database –Verbose
For more information refer to this link: https://msdn.microsoft.com/en-us/library/jj591621(v=vs.113).aspx
You are missing the set; in the field ID.

How to add Column in existing table in asp Boilerplate?

As you know Boilerplate don't give the entity classes to add columns and I want to add column in table named ( AbpUser). I tried to make a class in Migrations like below
public partial class AddRatingMig : DbMigration
{
public override void Up()
{
AddColumn("dbo.AbpUsers", "UserType", c => c.String());
}
public override void Down()
{
DropColumn("dbo.AbpUsers", "UserType");
}
}
Then in Pm console run command Update-Database
. But not successful. As you know Boilerplate don't give the entity classes to edit columns. Please Help Thanks in advance
The answer to this question is to Extend the AbpUser like this
public class User : AbpUser<User>
{
public string SpecialTitle { get; set; }
}
and add-migration UpdatedUserWithSpecialTitle
then update-database
Here is the correct way
public partial class AddRatingMig : DbMigration
{
public override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "UserType",
table:"AbpUsers",
nullable:true
);
}
public override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name:"UserType",
table:"dbo.AbpUsers"
);
}
}
Hence update Database using code as: update-database
NOTE:
Make sure that you have properly added migrations as:
add-migration migration_name
I had the same problem in abp.io framework, adding new property, "PICUstomerId" to AbpUser Entity and migrate it to database.
Here is the comments by abp.io:
Add your own properties here. Example:
public string MyProperty { get; set; }
If you add a property and using the EF Core, remember these;
Update PasargadInsuranceDbContext.OnModelCreating to configure the mapping for your new property
Update PasargadInsuranceEfCoreEntityExtensionMappings to extend the IdentityUser entity and add your new property to the migration.
Use the Add-Migration to add a new database migration.
Run the .DbMigrator project (or use the Update-Database command) to apply schema change to the database.
and finally add-migration to your solution and then update-database
1. Add your own properties here
2. Update PasargadInsuranceDbContext.OnModelCreating
3. Update PasargadInsuranceEfCoreEntityExtensionMappings to extend theIdentityUser entity
4. And finally after update-databse, I saw my new property in database

VS Community 2015 MVC Template - Cannot access custom model

I'm currently learning Asp.NET MVC, I have started with the Ouf of the Box template from Vs2015 but I am having problems getting data from custom table
Goal: My Goal is to add a contact list for the standard ApplicationUser using the following class:
public class UserContact
{
[Key]
public virtual int Id { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ApplicationUser Contact { get; set; }
}
I have also added the following to my Application User:
public virtual ICollection<UserContact> ContactsList { get; set; }
And the following line to my ApplicationDbContext:
public DbSet<UserContact> UserContacts { get; set; }
The problem is that when I try to access the USerContacts table from my custome controller ContactController using
ApplicationDbContext db = new ApplicationDbContext();
var UserId = SomUserID
db.UserContacts.Where(x => x.User == UserId)
The where clause does not get recognised at all. I have useed the commands
enable-migration
add-migration ContactsList
update-database
Which ran with no errors and the table is now in the database. But I am unable to access the table. why? what am I doing wrong?
Please note that according to VS it is as if the .Where function is not available on the DbSet in my case
And linq is imported as this is the standard when adding a new empty controller with Vs2015.
The Database was created during the update-database
But ApplicationDbContext : IdentiyDbContext class does not let me access any other tables including Contact class, so,
when I used in my controller
"db.UserContacts.Where < x => x.User == someID >();"
it doesn recognise what x.User is from the UserContact class.
EDIT: I found a stack overflow post where the user was missing a using statement:
using System.Linq;
DbContext -> DbSet -> Where clause is missing (Entity Framework 6)

Merge IdentityDbContext and DbContext ASP.NET MVC

I would like to only have one DbContext in my ASP.NET MVC project. How should I merge the default IdentityDbContext with my own code first DbContext? They are using the same database.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("SignalRChat")
{
}
}
This is the default one provided in the IdentityModel.cs class.
Is it safe to do the following? And append my own DbSets?
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("SignalRChat")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
Any advice is much appreciated!
Yes, it is perfectly fine to add DbSet declarations in the DbContext classes. Normally you would maybe create a context for a related group of tables that makes sense when you access it from your repositories, e.g. ApplicationDbContext for user registration, login etc. another for Students and related entities.
If you have many contexts maybe you should check for the bounded context "pattern" https://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/DEV-B336#fbid=wH4n-081m_U.

MVC5 and Entity Migrations with Asp.Net Identity

I have an issue that I have been struggling with. I would appreciate any help
So, I have an application that uses Code first. For authentication, I use Asp.Net Identity 2.0.1. So I have a User class that derives from Identity User like this:
public class User: IdentityUser
{
public virtual UserInfo UserInfo { get; set; }
public virtual Organization Organization { get; set; }
}
Then i define my Context as:
public class IdentityContext: IdentityDbContext<User>
{
public IdentityContext(): base("Name=IdentityContext")
{
}
static IdentityContext()
{
Database.SetInitializer<IdentityContext>(new CreateDatabaseIfNotExists<IdentityContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new UserInfoMap());
}
}
Then i enable migrations using this context. And since Organization class is linked to User it also is added to the migration. But I dont want that, since its different from the Identity classes. My Organization class is as follows:
public partial class Organization: EntityBase
{
public Organization()
{
this.Users = new List<User>();
}
public int OrganizationId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public virtual ICollection<User> Users { get; set; }
}
This derives from EntityBase and not from IdentityUser class and is handled differently.
What I would be able to do is to handle all my non-identity classes through a different context, lets say AppContext that could be defined as:
public class AppContext: DbContextBase
{
public AppContext(): base("Name=IdentityContext")
{
}
static AppContext()
{
Database.SetInitializer<AppContext>(new CreateDatabaseIfNotExists<AppContext>());
}
public new IDbSet<T> Set<T>() where T : class
{
return base.Set<T>();
}
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Configurations.Add(new OrganizationMap());
}
}
And then enable a second migration for this context.
But when I enable a second migration it fails with the exception that "Migrations have already been enabled in project 'Datastore'. To overwrite the existing migrations configuration, use the -Force parameter.". Although it still creates the Configuration file for the second migration.
So when i try to add a migration for this configuration it complains the following:
One or more validation errors were detected during model generation:
Datastore.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no
key defined. Define the key for this EntityType.
Datastore.IdentityUserRole: : EntityType 'IdentityUserRole' has no key
defined. Define the key for this EntityType.
Datastore.UserInfo: : EntityType 'UserInfo' has no key defined. Define the key for this
EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type >'IdentityUserLogin' that has no> keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type >'IdentityUserRole' that has no
keys defined.
UserInfoes: EntityType: EntitySet 'UserInfoes' is based on type 'UserInfo' that has no >keys defined.
I am not sure how to get around this? Any help is really appreciated
The idea was to inherit the AppContext with IdentityDbContext. IdentityDbContext itself inherits from DbContext so it has all the functionality available for DbContext plus extra configuration requirements for the Asp.Net Identity framework

Resources