Tell UserManager to use AspNetRoles - asp.net-mvc

I am trying to migrate a MVC3 Application to MVC5. I have Used these Articles:
http://www.asp.net/identity/overview/migrations/migrating-an-existing-website-from-sql-membership-to-aspnet-identity
http://www.codeproject.com/Articles/682113/Extending-Identity-Accounts-and-Implementing-Role
The old Application use the Database First Model (modeled with the EDMX file).
When I try to update the Role of a User I got following Error:
Additional information: The entity type IdentityRole is not part of the model for the current context.
In this Method (um.AddToRole):
public bool AddUserToRole(string userId, string roleName)
{
var um = new UserManager<AspNetUsers>(
new UserStore<AspNetUsers>(new Entities()));
var idResult = um.AddToRole(userId, roleName);
return idResult.Succeeded;
}
How Can I tell the UserManager to Use the AspNetRoles Class?
Best Regards,
Marko
AspNetUsers
namespace NursingHome.Models
{
using System;
using System.Collections.Generic;
public partial class AspNetUsers
{
public AspNetUsers()
{
this.AspNetUserClaims = new HashSet<AspNetUserClaims>();
this.AspNetUserLogins = new HashSet<AspNetUserLogins>();
this.NursingHome = new HashSet<NursingHome>();
this.AspNetRoles = new HashSet<AspNetRoles>();
}
//public string Id { get; set; }
//public string UserName { get; set; }
//public string PasswordHash { get; set; }
//public string SecurityStamp { get; set; }
public string Discriminator { get; set; }
public System.Guid ApplicationId { get; set; }
public string LegacyPasswordHash { get; set; }
public string LoweredUserName { get; set; }
public string MobileAlias { get; set; }
public bool IsAnonymous { get; set; }
public System.DateTime LastActivityDate { get; set; }
public string MobilePIN { get; set; }
public string Email { get; set; }
public string LoweredEmail { get; set; }
public string PasswordQuestion { get; set; }
public string PasswordAnswer { get; set; }
public bool IsApproved { get; set; }
public bool IsLockedOut { get; set; }
public System.DateTime CreateDate { get; set; }
public System.DateTime LastLoginDate { get; set; }
public System.DateTime LastPasswordChangedDate { get; set; }
public System.DateTime LastLockoutDate { get; set; }
public int FailedPasswordAttemptCount { get; set; }
public System.DateTime FailedPasswordAttemptWindowStart { get; set; }
public int FailedPasswordAnswerAttemptCount { get; set; }
public System.DateTime FailedPasswordAnswerAttemptWindowStart { get; set; }
public string Comment { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<AspNetUserClaims> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogins> AspNetUserLogins { get; set; }
public virtual ICollection<NursingHome> NursingHome { get; set; }
public virtual ICollection<AspNetRoles> AspNetRoles { get; set; }
}
}
AspNetUsers Extension
public partial class AspNetUsers : IdentityUser
{
}
AspNetRoles
public partial class AspNetRoles
{
public AspNetRoles()
{
this.AspNetUsers = new HashSet<AspNetUsers>();
}
//public string Id { get; set; }
//public string Name { get; set; }
public virtual ICollection<AspNetUsers> AspNetUsers { get; set; }
}
AspNetRoles Extension
public partial class AspNetRoles : IdentityRole
{
public AspNetRoles(string name)
: base(name)
{
}
}
DB Context Extension
public partial class Entities : IdentityDbContext<AspNetUsers>
{
public Entities()
: base("NursingHomesEntities")
{
}
}
Update
Installed Packages
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.AspNet.Identity.Core
Install-Package EntityFramework
Install-Package Microsoft.AspNet.Mvc
Install-Package Twitter.Bootstrap.MVC
Install-Package Microsoft.AspNet.Identity.Samples -Pre
Install-Package FontAwesome
Next Steps
EDMX File added (from database created)
Added one table with reference to AspNetUser.
Now I get following error:
Model compatibility cannot be checked because the DbContext instance was not created using Code First patterns. DbContext instances created from an ObjectContext or using an EDMX file cannot be checked for compatibility.
Is it not possible to use edmx file and mvc5 together?

First I recommend to use, a new asp.net identity 2.0 beta: https://www.nuget.org/packages/Microsoft.AspNet.Identity.Core/2.0.0-beta1
It is better and more flexible to override and use. You can get some information, samples and other things here: http://blogs.msdn.com/b/webdev/archive/2014/02/11/announcing-preview-of-microsoft-aspnet-identity-2-0-0-beta1.aspx
I can't reproduce this error, but probably is in the mapping configuration, a entity framework error and not a asp.net MVC error..
You need to take some care, replace all uses of dbcontext in your app, there is a topic to take a look to avoid this error: The entity type <type> is not part of the model for the current context
If is still not working, try make some tests and experiences or add more information here.

Related

Update hierarchy model in Entity Framework

I have two model classes:
Request:
public partial class Request
{
public long Id { get; set; }
public string Username { get; set; }
public string Description { get; set; }
public System.DateTime CreateDate { get; set; }
public long DeviceId { get; set; }
public bool IsFinalized { get; set; }
public Nullable<long> ParentId { get; set; }
public virtual Device Device { get; set; }
}
Device:
public partial class Device
{
public Device()
{
this.Requests = new List<Request>();
}
public long Id { get; set; }
public string Serial { get; set; }
public string AssetNumber { get; set; }
public System.DateTime CreatedDate { get; set; }
public virtual ICollection<Request> Requests { get; set; }
}
I have to update the models I use this method
public void Update(RequestViewModel viewModel)
{
var entity = _mappingEngine.Map<Request>(viewModel);
_requests.Attach(entity);
_uow.Entry(entity).State = EntityState.Modified;
}
but only Request model is updated after calling the Update method. I want to update both models. Please help me.
Attaching an entity to a DbContext, mark the attached entity and all its dependencies (i.e. associated entities) UnChanged. So its you who must tell EF what entities are new and what entities were modified.

add virtual field to model in mvc3

This is my model class.
namespace Details.Models
{
public class COMPLETE_DETAILS
{
[Key]
public long COMPLETE_DETAIL_ID { get; set; }
public string TRUCK_NO { get; set; }
public string CHALLAN_NO { get; set; }
public string L_R_NO { get; set; }
public string DEALER_NAME { get; set; }
public string SOURCE_DESTINATION { get; set; }
public string ORIGINAL_DESTINATION { get; set; }
public string COMPANY_DESTINATION { get; set; }
public decimal? CEMENT_BAG_NO { get; set; }
public decimal? RATE_PER_BAG { get; set; }
public decimal? TOTAL_COST_PERSONAL { get; set; }
public decimal? TOTAL_COST_COMPANY { get; set; }
public decimal? NET_PROFIT { get; set; }
public Nullable<DateTime> DATE { get; set; }
public decimal? OTHER_EXPENSES { get; set; }
**public virtual long? ROW_NO { get; set; }**
}
}
i want to add a virtual field to my model class but it`s not worked for me. In my data Base the table name is COMPLETE_DETAILS and it has all the field except ROW_NO so there is any another option to make a virtual field in model class of mvc3
I assume that you are using for example Entity Framework to link for example your MS-SQL database with c# class. So, you can list all required properties in c# class and then create new class inherited from COMPLETE_DETAILS with one extra field ROW_NO and calculate it programmaticaly or whatever you wish.
public class COMPLETE_DETAILS_CUSTOM: COMPLETE_DETAILS
{
public virtual long? ROW_NO { get; set; }
}
Some linq code:
using(DbContext Db = new DbContext())
{
List<COMPLETE_DETAILS_CUSTOM> items = Db.COMPLETE_DETAILS_DBSET.Select((item, index)=> new COMPLETE_DETAILS_CUSTOM(){
COMPLETE_DETAIL_ID = item.COMPLETE_DETAIL_ID,
// same with other fields
ROW_NO = index
}).ToList();
}

MVC4 Entity Framework and Simplemembership Re-Creation

Ok so I'm adding on to the Simplemembership.
Model UsersProfiles
namespace OilNGasWeb.Models
{
[Table("Users")]
public class UserProfiles
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Initials { get; set; }
public string Company { get; set; }
public string Department { get; set; }
public string Title { get; set; }
public string Team { get; set; }
public string TeamSub { get; set; }
public string Phone { get; set; }
public string ImageLocation { get; set; }
public string CurrentlyAuthorized { get; set; }
public string Note { get; set; }
public string Comment { get; set; }
//public virtual dbClient Client { get; set; }
public virtual ICollection<Roles> Roles { get; set; } //many to many
public virtual ICollection<dbClient> Clients { get; set; } // many to many
}
}
Roles
namespace OilNGasWeb.Models
{
[Table("webpages_Roles")]
public class Roles
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[Required(ErrorMessage = "Required")]
public int RoleID { get; set; }
[Required(ErrorMessage = "Required")]
public string RoleName { get; set; }
public virtual ICollection<UserProfiles> UserProfiles { get; set; } //many to many
}
}
My issue now that i have it creating the many to many tables like i saw it creat before modifications my question is how to get those tables Renamed
webpages_UsersInRoles
I would prefer not to go into SSMS and change them physically rather tell MVC to use a different instance
From the code above EF produced RolesUserProfiles instead of webpages_UsersInRoles
The error shows when the program is trying to #if (User.IsInRole("Administrator")) validade user.
Naturally I hit F12 on IsInRole to bring me to the definition....
it does but there all empty
Now what ? how can i recode if its hidden from me ? where is the code at , and how can i Modify this?
What i would like out of all this is
either renaming the tables ManytoMany as they are being created
being able to modify the code that looks for webpages_UsersInRoles
Thanks in advance.
You cannot rename the tables. The table names are hard coded in SimpleMembership. You can see the source code here:
http://aspnetwebstack.codeplex.com/SourceControl/latest#src/WebMatrix.WebData/SimpleMembershipProvider.cs
Don't use the EF navigational properties. You should be accessing this information via the Membership or WebSecurity API's.
If you really want to do this, then you will need to configure EF to use the tablenames required by simple membership, which means utilizing the fluent mapping syntax.. which is not exactly intuitive.

Mapping suggestion for a possibly shared foreign key (value object in entity) in Entity Framework 4.1?

I have a Project entity and an Rfi entity. The project entity contains a list of TeamMembers. Project is a navigation property in the Rfi entity. In the Rfi entity there is a RecipientId. This Id represents a person from the TeamMembers collection. So imagine, on a web page, we have a drop down box named Recipient. The list includes all team members of the Project. The user will select a Contact from that list. The Id of that contact will be saved in the RecipientsId property. When the page is reloaded we will select the Id of that user in the drop down based off the value in the RecipeintsId property. What is the best way to map this in EF 4.1 using the fluent API?
public class Project : BaseEntity
{
public string ProjectNumber { get; set; }
public string Description { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public string Currency { get; set; }
#region Navigation Properties
public Guid AddressId { get; set; }
public virtual Address Address { get; set; }
public Guid CompanyCodeId { get; set; }
public virtual CompanyCode CompanyCode { get; set; }
public virtual ICollection<Contact> TeamMembers { get; set; }
#endregion
}
public class Rfi : Document
{
public string Number { get; set; }
public string Subject { get; set; }
public string SubcontractorRfiReference { get; set; }
public string SpecificationSection { get; set; }
public RfiStatus RfiStatus { get; set; }
public Guid RecipientId { get; set; }
#region Navigation Properties
public Guid ProjectId { get; set; }
public Project Project { get; set; }
#endregion
}
As I understand it your problem is mapping between Rfi and Contect - Project doesn't have any role in your Recipient functionality from the database perspective.
You need either Recipient navigation property in Rfi or Rfis navigation property in Contact. EF code first needs navigation property on at least one side of the relation.
So you can use something like:
public class Rfi : Document
{
public string Number { get; set; }
public string Subject { get; set; }
public string SubcontractorRfiReference { get; set; }
public string SpecificationSection { get; set; }
public RfiStatus RfiStatus { get; set; }
#region Navigation Properties
public Guid RecipientId { get; set; }
public Contact Recipient { get; set; }
public Guid ProjectId { get; set; }
public Project Project { get; set; }
#endregion
}
And map:
modelBuilder.Entity<Rfi>()
.HasRequired(r => r.Recipient)
.WithMany()
.HasForeignKey(r => r.RecipientId);

Define the key for this EntityType

I get this error on this line of code -
ReportRunnerEntities reportDB = new ReportRunnerEntities();
public ActionResult Index()
{
**var types = reportDB.ReportTypes.ToList();**
return View(types);
}
The tables in the databse have primary keys defined and identities set.
My models are -
namespace ReportRunner.Models
{
public partial class ReportRunnerEntities : DbContext
{
public DbSet<Reports> Report { get; set; }
public DbSet<ReportTypes> ReportTypes { get; set; }
public DbSet<Users> Users { get; set; }
}
}
namespace ReportRunner.Models
{
public partial class ReportTypes
{
public int ReportTypeId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Reports> Reports { get; set; }
}
}
namespace ReportRunner.Models
{
public class Reports
{
public int ReportId { get; set; }
public int ReportTypeId { get; set; }
public int UserId { get; set; }
public string Title { get; set; }
public ReportTypes ReportType { get; set; }
}
}
namespace ReportRunner.Models
{
public partial class Users
{
public int UserId { get; set; } //ArtistId
public string Name { get; set; }
}
}
and here is my connection string -
I suspect that it's never reaching the database. As I said the keys are set in the database.
Am I missing something?
There are a couple things I see that should change:
ReportTypes should be ReportType
public List Reports { get;
set; } should be public
ICollection Reports { get;
set; }
If you are defining a
connection string in your web.config,
you need to tell EF what one it is
using the constructor in your
ReportRunnerEntities class like this:
namespace ReportRunner.Models
{
public partial class ReportRunnerEntities : DbContext
{
public ReportRunnerEntities : base("name=NameOfConnectionInWebConfig")
{}
public DbSet<Reports> Report { get; set; }
public DbSet<ReportTypes> ReportTypes { get; set; }
public DbSet<Users> Users { get; set; }
}
}
You can read more on that here : http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
Just on a side note, if you are planning on using .NET MVC and EF Code First as your stack, I would start using the Repository and Unit of Work pattern. Here is a good post on how to set that up: Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable

Resources