I have an asp.net mvc project that uses asp.net Identity to authenticate users. The database has been designed in entity framework designer.
There is a table named "Farmers" and I want to allow each farmer to login to the application. As I know in order to achieve this, the farmer must inherit from IdentityUser, but how can I do this in entity framework designer?
what is your mvc version??
in mvc5 this is a good response
http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx
for this way u can mixed the two tables.
the other way is create an relationship between the two tables an use
User.Identity.Name or
User.Identity.GetHashCode
an use this to obtain the values of connected user
After a lot of hours of research I figured out that inherit from ApplicationUser or IdentityUser is not possible using the Entity Framework Designer.
My solution is to create a Code First Model from the existing database and then inherit from ApplicationUser.
As far as I know you can't really do that and I would argue that you shouldn't even try to do that even if you could.
By inheriting from IdentityUser you are saying that the Farmer can be described by properties like SecurityStamp, Roles or PasswordHash (inherited from IdentityUser) which does not make that much sense from a design point of view.
If what you are looking for is having a direct association between a user and a farmer you could simply add a required UserId property in you Farmer model. So whenever you create a new UserIdentity instance you also create a new Farmer instance as well with the UserId set to be the Id property of the newly created UserIdentity.
Related
I've got an architecture issue that I'm hoping someone can be of assistance to guide me in a more ideal strategy. The way I've been forced to do this reeks of "code smell".
I've got two different kinds of "Roles". I've got the built in Identity Roles, and I've got a custom set of roles (User Group Roles). I store these User Group Roles in a database, essentially a relationship between a user id, a usergroup role id, and a usergroup id. I'm using Ninject for dependency injection of my UserGroupService that handles all the CRUD operations of assigning users with certain usergroup roles to usergroups.
My first plan of attack was to create a custom authorization attribute that I could place on actions, similar to the Identity [Authorize(Role="")] attribute. I did not have any luck with this because I cannot inject a service into an attribute class (needs a parameterless constructor).
After that didn't work, my second plan of attack was to write an extension method for IPrincipal, essentially mimicking User.IsInRole("") with User.IsInUserGroupRole(""). This didn't work because I cannot inject a service into a static class.
Currently I am stuck including some booleans in the model of every view that has role based logic involved. So for instance:
public ActionResult Navigation()
{
var isSystemAdmin = User.IsInRole("Administrator");
var isUserGroupAdmin = _userGroupService.IsUserGroupAdmin(User.Identity.GetUserId()) && !isSystemAdmin;
var isGeneralUser = !isSystemAdmin && !isUserGroupAdmin;
var model = new NavigationViewModel
{
IsSystemAdmin = isSystemAdmin,
IsUserGroupAdmin = isUserGroupAdmin,
IsGeneralUser = isGeneralUser
};
return PartialView("_Navigation", model);
}
The issue here is that I have to do this any time I want to determine what kind of roles the user is currently in. It works, but it smells.
Am I missing something here? I think the most ideal option would be the extension method strategy of being able to call it right off of User, but cannot seem to make that work.
Constructor DI is not the only way to get access to a dependency.
Each IOC has a way of resolving a dependency, all you need is a reference to the IOC container. So, even if your attribute requires a parameterless constructor you could still resolve the dependency manually.
Something like this should help :
http://www.c-sharpcorner.com/UploadFile/47fc0a/resolving-dependency-using-ninject/
Is it a great way to use your IOC this way? Probably not but it sure beats what you're doing now.
I am using a boiler-plate VS2013 generated project (Code First, Migrations).
I wish to take the easy route and use all the built-in Identity API for handling of authentication and accounts (register, login all that).
Yet I wish to have a separate user table (let’s call it AppUser) with its own attributes that is not part of Identity because I am implementing my own domain with other relationships (Company => user hierarchy, Documents, etc) this is all admin’d outside of Identity by my custom pages. The AspNetUser would have already registered his account prior to my custom pages wiring him in.
My issue is how do I setup a relationship in the context from AppUser to AspNetUsers.
I thought this would be pretty simple but I am lost.
The only thing I can come up with is to have AppUser have a string called AspNetUser_ID that I would manually join to the AspNetUser table.
This seems pretty brittle and I would prefer it could have a FK constraint.
The other thing I cannot figure out is how to get AspNetUser in my DBContext so it is accessible.
Any help would be great.
Since you're using the boilerplate template, you should be able to find a class file named IdentityModels.cs in the Models folder. There, you can find the ApplicationUser class, to which you can add all the extra properties you want, as with any other Code First entity. This is the entity that maps to the AspNetUsers table. Here you could just add your AppUser class as a navigation property, or maybe, to keep things simple, add the properties from AppUser to ApplicationUser, so you only have one ***User entity to deal with.
I'm reading a book written by Julie Lerman on Code First. According to the book, annotations and fluent api give the same result. Everything depends on the style of the developer.
I know that annotations allow both to configure how code first generate database objects and how MVC customize UI elements. Let's say I use [Required, MaxLength(50)]. The attribute will generate a NOT NULL, nvarchar (50) in the database. It also will validate the input for that field.
[Required, MaxLength(50)]
public string Name { get; set; }
What if I decide to use Fluent API to configure Code first. Am I still going to need annotations to influence UI elements or using fluent API is going to be enough?
EDIT
How about annotations, such as Display that serve only for UI purposes? Do they have equivalents? If not, Will I need to use annotaions?
[Display(Name = "Date of Birth")]
public DateTime BirthDate { get; set; }
Thanks for helping
Data Annotation is the simplest way of telling a class to enforce some validation rule. You can do the same thing with Fluent API as well. Some people like doing it by data annotations and some people like it by doing with fluent API
Reasons to like it with Data Annotations
1) Keep the validation info about my entity in one place along with the entity definition
Reasons to like it with Fluent API
1) Keep my entity clean. It will have only my property info. No validation info. Clean and simple POCO. I will write validation on the OnModelCreating method in my data context class.
You can not do all Fluent API things with Data Annotations way. the same way you don't have few Data Annotations attributes equivalant not present with Fluent API way ( Ex : HasMinLength) . HasMinLength is something we will for our Model validation which usually makes sense in the UI.
For the UI Model Validation, you can not use the Fluent API alone. Fluent API's major role is to look into the fluent configuration we writes and act when creating the Model(Database) from the entities. Remember we are overriding the OnModelCreating method to write our fluent API configuration. So for the UI Validation (of my ViewModel), I would use the DataAnnotation way and use fluent API if i want to define some thing related to my datamodel like Define a foreign key or Map this Entity to a Table with different name etc..
EDIT : As per the question edit,
You should make use of the Data Annotations in this case. If you are doing code first. You may remember that that entity is going to be your Database table ( of course you can tell EF to ignore /rename specific columns). In that case, I would keep my Entities clean and Create a ViewModel which i will use in my UI. I will add my DataAnnotations in my ViewModel to handle it. I may write some mapping code which maps data from ViewModel to Model and Model to ViewModel wherever necessary.
If your entity model classes are doubling as your viewmodel classes, AND you are using the default out of the box DataAnnotationsValidationProvider, then you would need the dataannotations attributes on the model properties to get validation.
However, you should not double your entity classes as viewmodel classes. Take for instance, a controller that needs to have a ReturnUrl property in its model. You wouldn't want this in your entity model / database. Because of differences like this between the View model and the Entity model, the 2 should really be separate (yet cohesive) layers in your application. You can make them cohesive using a library like AutoMapper.
This is one of the reasons I prefer the fluent API. If you stick to the fluent API, then you would never put any attributes on any entity model classes or properties. When it comes time to show, insert, or update data, you put the attributes on the viewmodel classes only.
Also, the [Required] attribute on an entity type performs validation during SaveChanges, whereas a [Required] attribute on a viewmodel performs validation during model binding.
According to Julie Lerman's book on DbContext, you do NOT need any additional annotations to your Fluent API configuration. The Name property will get validated by Validation API as if it had been configured with Data Annotations.
According to the same book, MaxLength and Required are the only validation attributes with fluent API conterparts.
I am trying to implement a custom membership provider in ASP.NET MVC 3 with the Enitty Framework. For the user data I created a User class that holds all the login data plus some more.
When I tried to implement the MembershipProvider, some methods appeared that I need to implement which have a MembershipUser parameter in the signature:
public override void UpdateUser(MembershipUser user)
I know I can make my User class inherit the MembershipUser class and this won't be a problem. But when I tried to make it inherit, I couldn't set values for the readonly properties, like Email and others.
Is there any way that these methods can accept an object of type User? Or maybe there is some other better approach to this?
References
http://msdn.microsoft.com/en-us/library/ms152065.aspx
Custom MembershipUser with only needed parameters
http://www.codeproject.com/Articles/165159/Custom-Membership-Providers
Answer
You can create instances of MembershipUser and pass the properties (readonly or not) on the constructor, and then return that MembershipUser instance.
The documentation for the MembershipUser class has a quote that helped me to understand this better:
Creating a new MembershipUser object does not add a new membership
user object to the membership data store.
If adding the custom properties is important that will require you to subclass MembershipUser.
For an example see: Custom MembershipUser with only needed parameters
The last reference link shows a nice article with a custom membership provider using Linq-to-Sql rather than EF but the similarities are many.
Hope that helps.
I need just a few confirmation that I do some stuff in the right way or I make horrible mistake :)
1) I put my data access layer (MyProject.Domain) in sepparate assembly. There I have entity object "User" that has properties in 1:1 relation with "User" table in my database. I also extend this user from "MembershipUser" because I use custom schema for membership. Is this good location to store MembershipUser entity?
2) I have "Image" table in database and "Image" entity in my domain library. Image in database has "AuthorId" column which is FK to "User" table. Also image contain list of "comments". So I structure Image domain object like this:
public class Domain
{
public int ImageId{get;set;}
public string Name{get;set;}
public Author Author{get;set;}
public IEnumerable<Comment> Comments{get;set;}
}
Is this good way or maybe I should assemble all data in a ViewModel class?
You should really make a distinction between domain models and view models. Domain models are those classes that represent your domain business entities. It could be EF autogenerated classes or whatever. So even being aggregate classes they are still domain models as they aggregate domain entities and could be stored alongside with other domain models.
View models are classes that are specifically defined for a given view. The view models are always defined inside the ASP.NET MVC project because they are tightly coupled to specific views which are themselves defined in the ASP.NET MVC project. Domain models could be defined in separate assembly. They are intended to be resused in other applications as well. Think of your domain models as the core of your business. If tomorrow ASP.NET MVC is no longer modern, and something else comes out you should still be able to reuse your domain models. The view models are only a specific representation of your domain models for some given and specific view.