How to Incorporate ASP.NET User Data in MVC Models

Hi Experts.  I'm just learning MVC5 and am having some trouble finding an example that shows me how I would model my data so that a table in which the ID of the creator of a record must be recorded.  The AspNetUsers table that is automatically created the first time a user registers on my site contains an Id field (nvarchar(128)) and my Company model includes a "CreatedBy" field which should have a one-to-many relationship with the AspNetUsers table.  Ultimately, users should only be able to view and interact with records related to the companies they have created (or to which the creator has given them permissions).  If I was doing a Database First project I would just create the relationship between the entities and Visual Studio would do the rest.  But this is a Code First project and I don't know how to make it happen.  Can you help?  Please let me know if you need additional information of clarification (I'm still learning the terminology so forgive me if I've gotten some of it wrong).  Thanks!

Company.cs (Model)
    public class Company
    {
        [Key]
        [Required]
        [ScaffoldColumn(false)]
        public int CompanyId { get; set; }

        [Required]
        [DataType(DataType.Text)]
        [StringLength(50, ErrorMessage = "Company name may not be more than 50 characters long.")]
        [MinLength(3)]
        [Display(Name = "Company Name")]
        public string CompanyName { get; set; }


        [Required]
        [DataType(DataType.Text)]
        [ScaffoldColumn(false)]
        public string CreatedBy { get; set; }

        [Required]
        [DataType(DataType.DateTime)]
        [ScaffoldColumn(false)]
        public System.DateTime Created { get; set; }

        public virtual ICollection<Item> Items { get; set; }

        public virtual ICollection<Category> Categories { get; set; }
    }

Open in new window


DatabaseInitializer.cs
        private static List<Company> GetCompanies()
        {
            var companies = new List<Company> {
                new Company {
                    CompanyId = 1,
                    CompanyName = "MyCompanyName",
                    CreatedBy = [Current USERID from AspNetUsers],
                    Created = System.DateTime.Now
                },
            };

            return companies;
        }

Open in new window

LVL 1
penlandtAsked:
Who is Participating?
 
Craig WagnerSoftware ArchitectCommented:
I'm not sure whether you're asking how to create a foreign key or how to populate the CreatedBy field. I'm going to assume the latter.

My suggestion would be to put the name of the user in the CreatedBy field as that is more readily available and can be used more easily when you're trying to enforce the business rule that a user can only interact with rows they created. To do that just set CreatedBy to the thread identity.

CreatedBy = Thread.CurrentPrincipal.Identity.Name

Open in new window


If you ever need to load the ApplicationUser you can do so by querying off the name.
0
 
Bob LearnedCommented:
If you are talking about Code First design with the Entity Framework, and you are looking for a way to create entity relationships, then you can do that work in the context.

Code First Relationships Fluent API
https://msdn.microsoft.com/en-us/data/hh134698.aspx?f=255&MSPPError=-2147217396

modelBuilder.Entity<Post>().HasRequired(p => p.Blog) 
                .WithMany(b => b.Posts) 
                .HasForeignKey(p => p.FKBlogId);

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.