How to simply update entity in entity framework? - asp.net

I'm writing a custom .NET MembershipProvider (not the built in one) and trying to update using Entity Framework. But of course i have no access to (Try)UpdateModel. How can i update it? Thanks in advance.

You can't do this kind of thing with the ASP.NET Membership Provider, that is, write custom updates to the tables.
If it were that easy, less people would have issues/problems with it. =)
Don't even bother adding the ASP.NET Membership SQL Tables onto your EDMX - you won't know the relationships or how the tables really work together. Forget about trying to represent it as a "Model".
My advice is don't try and bind to the MembershipProvider as a Model (i.e dont create a strongly typed view), just call the Membership methods directly from your controller.
This is where we start to miss the 'drag and drop' of Web Forms, can't drop on a ChangePassword control. =)
Your best bet would be to create a regular view (not strongly typed), then have regular buttons that post to your controller methods.
Don't try and pass through the object as a model, get the fields in the Request.Form collection.
[HttpPost]
public ActionResult ChangePassword()
{
string userName = Request.Form["userName"];
string passWord = Request.Form["passWord"];
MembershipProvider.ChangePassword(userName, password);
return View("ChangePasswordSuccess");
}
The above code would be (roughly) the equivalent of passing through a strongly typed User object, changing the password and calling UpdateModel.
Of course, you could implement your own membership provider, but i dont believe implementing a custom provider just to make your code "easier" should be the driver, because unless coded properly (which is not easy to do), you compromise a lot of the built-in security features and wealth of account management options of the ASP.NET Membership provider that we take for granted.

To do this with the default provider is a little complicated, however what would be much easier would be to create your own CustomMembershipProvider as outlined here:
Implementing A Membership Provider
As you can do this to your OWN account model, you can code the repository/DAL code however you choose, and use standard EF practices and conventions, allowing you to perform simple and strongly mapped operations such as UpdateModel.

A similar question was asked here.
Here is a CodeProject sample app that could get you started that uses EF and Microsoft's MembershipProvider. There is a class they built that inherits from MembershipProvider.
http://www.codeproject.com/KB/web-security/EFMembershipProvider.aspx

Related

How to create user without using Membership.CreateUser()?

Will someone please tell me how to create a user without using membership.createuser() and create user wizard in asp.net? I need to perform an additional insert on an existing table during CreateUser().
Here are two ways to go:
Implement your own custom membership provider. This is easier than you think and pretty straight forward. There are plenty of articles around.
or
To save you some time... implement your own custom membership provider and inherit from the SqlMembershipProvider class. In the subclass you will mostly just "forward" the calls to the base class except for in the CreateUser method. In this case you can let the base class do most of the work and then perform your custom insert. However, since it does need to be in one transaction (per your comment above) then things might be a little hairy... and you would possibly have to reimplement the CreateUser method in your subclass.
http://msdn.microsoft.com/en-us/library/system.web.security.sqlmembershipprovider.aspx
Note: I am on a bus right now via Wifi, but I am almost tempted to write this for you if you include the emp_details schema for me. Are you using straight ADO.NET or something else?

Elegant validation techniques for Entity First MVC3 site?

Having never done an MVC site I am about to start a project for a very large one. I feel confidant enough to do it, but I have one thing I need help figuring out.
We are definitely going to be using an "Entity First" method and have a single .edmx file defining the models, there are multiple reasons for this but just know that this is a definite piece of the puzzle.
So the piece I need to figure out is how to come up with an elegant way to do validations against Entities on a page, without hand coding each page, at least for the majority of things.
Are there any already popular methods for doing some basic validations? Things like MaxLength or Required or MinDate, etc?
Anything more complex than that and I understand I'd have to code it myself, but this site is going to be very large and I really need to find a way to speed some of the basic tasks up.
EDIT
I should point out a couple important facts.
1) Our database already exists and was created by a DBA before developers even came into the picture.
2) There are hundreds of tables and stored procedures already created.
3) When changes will need to be made to the database, they will go through the DBA, who we will not always have instant access too.
First of all, if you use Entity Framework Code First, you don't have a .edxm file storing your models or relationships between them: you just write your POCO (Plain Old CLR Object) classes, and that's it — Code First will figure out the relations between your models based on naming conventions.
To validate your (view) models, I recommend using FluentValidation or DataAnnotations. Both let you define validation rules in one place, either using a fluent validation API in different entity validation classes (FluentValidation) or using attributes to decorate your entity properties (DataAnnotations). The advantage of DataAnnotations over FluentValidation is that you get additional client-side validation out of the box.
Whichever framework you choose, both ship with a bunch of predefined validation rules like Required, Range, or MaxLength (see Fluent Validation for .NET or System.ComponentModel.DataAnnotations Namespace for examples).
I would 100% absolutely still use some POCO class. Download the DBContext generator template that will then create the code first from your model, OR use the Entity Framework Power Tools to reverse engineer an existing database. The down side to these methods though is that you won't get client side validation, only when saving it will you get the validation. You can however still add your validation attributes if you so choose for client side validation in addition using
MetaData Classes to use Data Annotations on your properties and get client side validation using the built in jQuery unobtrusive validation.
However - what we're talking about here goes against the basic design of MVC good practices anyways. Ideally your views should have ViewModels that are at times only a portion of an entity, in this case your validation attributes are still generated on your properties as DataAnnotations in MetaDataClasses.
If you feel this is all too much work and you are fine with just the server validation and have made a decision not to use ViewModels and rely on the Entity Frameworks validation- or use ViewModels and still rely on EF validation, then you will need a handler like the following in your controller (or other layer that has been given access to ModelState) to catch the following exception. Note I use AutoMapper to copy the properties between my ViewModel to my Entity.
Entity Framework Power Tools (right click in your project in solution explorer after its installed and there will be an new 'Entity Framework' menu -> Reverse Engineer - note it doesnt generate [TimeStamp] attributes and forgets to put in schema names - besides that its pretty good)
[HttpPost]
public ActionResult Create(CustomerCreateViewModel customerViewModel)
{
if (ModelState.IsValid)
{
try
{
Mapper.CreateMap();
Customer customer = Mapper.Map(customerViewModel);
var repository = new CustomerRepository(db);
repository.Save(customer);
return RedirectToAction("Edit", new { id=customer.CustomerId});
}
catch (DbEntityValidationException ex)
{
foreach (var error in ex.EntityValidationErrors.First().ValidationErrors)
{
this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
return View();
}
}
return View(customerViewModel);
}
Jon Galloway has a nice article called Generating EF Code First model classes from an existing database which I think will help you greatly in getting your application up and going from what you described.
Secondly, from having built out our own MVC application so far, I've found that you're really not going to be working directly with Entity Framework models directly very often. Most of the time you'll end up with some type of view model for doing your gets and posts to. Adding DataAnnotations to those class properties will make it very easy for you to do your validations on the client side. Once you have validated the data from the client side and checked your entities against any business rules, you really should then be able to trust the data and use EF to do your basic CRUD work with.
Good luck, and hope this helps you some with your project.
What Marius is trying to tell you is that "Code First" refers to your "model" being defined by fluent code mappings that do not rely on an .edmx file. Therefore, if you're using an .edmx file, you're not doing "code first". You're doing either "Database First" or "Model First" (both of which use the .edmx).
In your case, you already have a database, so you're using the "Database First" approach, using EF 4.1 DbContext. This is not "Code First" (or as you incorrectly stated, Entity First). This is not a semantic quibble, as "code first" has a very specific meaning. This is not it.
Now, on to the rest of your question. Since all your database access has to go through stored procedures, Entity Framework is not a good choice in my opinion. You would be better off using something like nhibernate, which has much better stored procedure support.
EF is intended to represent your relational data model in objects, and generates all its own sql to access and fill these objects. If you have to go through the sprocs, EF will be a constant uphill battle for you.

Membership Provider

I am currently developing an web site using asp and have a few questions regarding Membership Provider.
I am currently inheriting from Membership Provider class and have just got over the issue of only certain parameters being able to be passed to the CreateUser method.
I have been able to overcome this issue by creating a class that inherits from MembershipUser adding custom properties and then passing that the the UpdateUser method. However to me this seems quite messy and not very efficient as I am making two calls to the database when I could do it in one if I dont use the CreateUserWizard.
So my question is, is using the Provided Login components worthwhile if you are overriding the methods and require more parameters ect in order to keep the use of the properties you can define for this class in the web.config file or is it easier in the long run to just start from scratch. Basically what I want to know is how people have found using Membership by overriding and inheritance over starting from scratch, and how these compare.
Any webpages that talk about this would be good and apologies if the question doesn't make sense or I have missed anything out.
Thanks,
Ric
If I am understanding your question correctly, then yes the membership provider is a great api to build off of so you don't have to reinvent the wheel for the basics of authentication/authorization.
You are using Membership wrong. You should only create your own custom provider when you need to map onto an existing database. IF you are making your own database, then you should just use the default implementation.
Even if you create a custom implementation, you should not do anything that the current membership doesn't already provide. Just map those functions on to your database.
To add additional information, you create a secondary table called UserData or something. This table will be keyed by the MembershipUser.ProviderUserKey, so you lookup any data you need from the other table using the userid from the membership class.
You're really fighting upstream trying to change membership to give you custom things. You can do it, but why cause yourself trouble?

Is it worth to write a custom Profile Provider?

I wrote a custom Membership Provider and it was relatively easy.
Now I need to create users with first name, last name and other fields not considered in the any of the MembershipProvider.CreateUser overloads.
I read that I should not overload CreateUser. Instead, I should write my own Profile Provider.
It seems like a lot of work and I am not sure of the benefits. Can you help me decide the right way to go? (It is for a MVC 3.0 web app.)
It depends. If it isn't a lot of info, you could just create a custom MembershipUser class with the appropriate additional fields. You can look at codeplex.com to find examples of custom Profile implementations.

Custom MembershipProvider with Web interface and DAL

I'm working on an ASP.NET solution with 2 projects. One is the web interface and the other contains my business logic. I'm using LINQ to SQL for my data access in the second project.
Apart of my database, I have a table called Users which holds user information.
I've started to implement a MembershipProvider. I notice that MembershipUser is coupled with MembershipProvider. What is the most correct way of getting my BLL/DAL to talk about Users?
Should I minimally implement MembershipUser and whenever a user calls a method, it will call for eg. GetUserInfo() in my BLL/DAL, to get complete information about the user?
Or should I make the MembershipUser class methods call my custom "Users" class methods (like a wrapper) in the BLL/DAL (this custom users class is not related to linq)?
Or can I somehow extend the Linq to sql class "CFUsers" to extend MembershipUser.
I hope this makes sense.
I usually see this a seperate entities as MembershipUser revolves around membership which is a generic concern and a user in your system revolves around whatever your domain entails, I do see your point of view where both these entities could be contained in one, so. Profiles is definitely the easiest way to go.
There's a walkthough on the MSDN docs at
http://msdn2.microsoft.com/en-us/lib...US,VS.80).aspx and a
good walkthrough from Scott Guthrie at
http://weblogs.asp.net/scottgu/archi...18/427754.aspx
As always It depends on what your goals are. Adding to Profile is a simple mechanism
for additional data. It requires very little in the way of customization and
makes the info easily available for the web application. This may not be
where you want to store this type of data; if not, it is a non-solution.
If this does not fit, making a new provider derived from the default (to
inherit what you already have) is a great option.
and of course the ultimate http://codesmart.wordpress.com/2009/03/27/extending-the-microsoft-aspnet-membership-provider/

Resources