Morgan Bengtsson
Morgan Bengtsson

Reputation: 1341

Associate forms authentication user to model

I am using forms authentication for a .NET MVC3 project. I am also using the EntityFramework for this. The user handling is pretty straight forward. Though the question is, how do I associate users to models?

Say I have a simple post model:

public class Post
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public DateTime Updated { get; set; }
    //public MembershipUser Author { get; set; }
}

Note the Author field. How do I link a user to it?

Upvotes: 1

Views: 341

Answers (2)

smartcaveman
smartcaveman

Reputation: 42246

I am assuming your Post object is a view model.

Create a flattened User object that has the information you need about the user for your view. If you were making a post view, like the ones on stackoverflow, this would might look like:

 public class User{
     public string DisplayName {get;set;}
     public string AvatarUrl{get;set;}
     public int Reputation {get;set;}
     public int GoldBadges{get;set;
     public int SilverBadges{get;set;
     public int BronzeBadges{get;set;
 } 

Then you would just add that property to your view model.

In situations where you are doing authentication like logging in, you probably want a separate input model, like:

 public class LogonModel{
      public string Username{get;set;}
      public string Password{get;set;}
      public bool RememberMe{get;set;}
 }

All the binding from the input models to your MembershipUser can take place in a ModelBinder, and your actual business logic should take place in your Controller.

Upvotes: 1

user553671
user553671

Reputation:

I'm using nHydrate and EF for an MVC3 project. After struggling to get MembershipUser and MembershipProvider to work with the nHydrate framework, I suddenly realized that I really had not particular need to use the ASP.NET Membership... stuff. In the end, it was much simpler to just include my own authentication methods in the data layer I was writing anyway.

So, FWIW, it might be worth your while to ask yourself just why you need to use the built-in Membership... stuff. If you're not tying into a legacy system, you may find that it's not buying you all that much.

Upvotes: 1

Related Questions