You must Sign In to post a response.
  • Category: ASP.NET

    ASPNetUsers as a foreign key in another table.

    Hi,

    CV MODEL CODE:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.ComponentModel.DataAnnotations;

    using System.ComponentModel.DataAnnotations.Schema;



    namespace LJLCV.Models

    {

    public class cvdetail

    {

    //////////////////////////////////////////////////////////


    **(Relevant code)**

    [Key, ForeignKey("ApplicationUser")]

    public string Id { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    **(Relevant code)**

    [Required(ErrorMessage = "First Name is required"), StringLength(100), Display(Name = "First Name")]

    public string FirstName { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "Last Name is required"), StringLength(100), Display(Name = "Last Name")]

    public string LastName { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "Address is required"), StringLength(300), Display(Name = "Address"), DataType(DataType.MultilineText)]

    public string Address { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "Landline is required"), StringLength(12), Display(Name = "LandLine")]

    public string LandLine { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "Mobile is required"), StringLength(12), Display(Name = "Mobile")]

    public string Mobile { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "Email Address is required"), Display(Name = "Email Address"), DataType(DataType.EmailAddress)]

    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",

    ErrorMessage = "Email Address is is not valid.")]

    public string Email { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "A personal statement is required"), StringLength(10000), Display(Name = "Personal Statement"), DataType(DataType.MultilineText)]

    public string PersonalStatement { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "Skils are required"), StringLength(500), Display(Name = "Skills"), DataType(DataType.MultilineText)]

    public string Skills { get; set; }



    //////////////////////////////////////////////////////////



    [Required(ErrorMessage = "Interests & Hobbies are required"), StringLength(50), Display(Name = "Interests & Hobbies "), DataType(DataType.MultilineText)]

    public string InterestsnHobbies { get; set; }



    //////////////////////////////////////////////////////////

    }

    }

    IDENTITYMODELS CODE:

    using System;

    using System.Security.Claims;

    using System.Threading.Tasks;

    using System.Web;

    using Microsoft.AspNet.Identity;

    using Microsoft.AspNet.Identity.EntityFramework;

    using Microsoft.AspNet.Identity.Owin;

    using Microsoft.Owin.Security;

    using LJLCV.Models;

    using System.Data.Entity;

    using System.ComponentModel.DataAnnotations.Schema;

    using System.Collections.Generic;

    using System.ComponentModel.DataAnnotations;



    namespace LJLCV.Models

    {

    // You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.

    public class ApplicationUser : IdentityUser

    {



    public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)

    {

    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType

    var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);

    // Add custom user claims here

    return userIdentity;

    }



    public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)

    {

    return Task.FromResult(GenerateUserIdentity(manager));

    }

    }



    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

    {

    public ApplicationDbContext()

    : base("DefaultConnection", throwIfV1Schema: false)

    {

    }



    public static ApplicationDbContext Create()

    {

    return new ApplicationDbContext();

    }

    }

    }



    namespace LJLCV

    {

    public static class IdentityHelper

    {

    // Used for XSRF when linking external logins

    public const string XsrfKey = "XsrfId";



    public const string ProviderNameKey = "providerName";

    public static string GetProviderNameFromRequest(HttpRequest request)

    {

    return request.QueryString[ProviderNameKey];

    }



    public const string CodeKey = "code";

    public static string GetCodeFromRequest(HttpRequest request)

    {

    return request.QueryString[CodeKey];

    }



    public const string UserIdKey = "userId";

    public static string GetUserIdFromRequest(HttpRequest request)

    {

    return HttpUtility.UrlDecode(request.QueryString[UserIdKey]);

    }



    public static string GetResetPasswordRedirectUrl(string code, HttpRequest request)

    {

    var absoluteUri = "/Account/ResetPassword?" + CodeKey + "=" + HttpUtility.UrlEncode(code);

    return new Uri(request.Url, absoluteUri).AbsoluteUri.ToString();

    }



    public static string GetUserConfirmationRedirectUrl(string code, string userId, HttpRequest request)

    {

    var absoluteUri = "/Account/Confirm?" + CodeKey + "=" + HttpUtility.UrlEncode(code) + "&" + UserIdKey + "=" + HttpUtility.UrlEncode(userId);

    return new Uri(request.Url, absoluteUri).AbsoluteUri.ToString();

    }



    private static bool IsLocalUrl(string url)

    {

    return !string.IsNullOrEmpty(url) && ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || (url.Length > 1 && url[0] == '~' && url[1] == '/'));

    }



    public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)

    {

    if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))

    {

    response.Redirect(returnUrl);

    }

    else

    {

    response.Redirect("~/");

    }

    }

    }

    }



    CVCONTEXT CLASS

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Data.Entity;

    using System.ComponentModel.DataAnnotations;

    using Microsoft.AspNet.Identity.EntityFramework;



    namespace LJLCV.Models

    {

    public class CvContext : DbContext

    {

    public CvContext(): base("DefaultConnection")

    {

    Database.SetInitializer<CvContext>(new DropCreateDatabaseIfModelChanges<CvContext>());

    }

    public DbSet<cvdetail> cvdetails { get; set; }


    **Relevant code
    protected override void OnModelCreating(DbModelBuilder modelBuilder)

    {

    modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);

    modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);

    modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });

    }
    **Relevant code

    }

    }

    Links to what I have tried:

    > https://forums.asp.net/t/2081436.aspx?Error+EntityType+IdentityUserLogin+has+no+key+defined+Define+the+key+for+this+EntityType+

    >http://stackoverflow.com/questions/28531201/entitytype-identityuserlogin-has-no-key-defined-define-the-key-for-this-entit

    Summary of what I'm trying to do:

    I'm trying to reference the 'Id' from 'AspNetUsers' as a foreign key in my model 'cvdetails'. The code above (highlighted in yellow), fixed the following error that I was getting when I was trying to run the application:

    LJLCV.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
    LJLCV.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
    IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
    IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

    Now the applications runs without any errors, and the application loads, I'm also able to register users without any problems.

    However when I go and check the database to see if the correct tables have been created I get this:

    Inline image 1

    So it creates all the usual 'AspNetUser' tables along with a duplication of those tables with: 'ApplicationUsers', 'IdentityRoles', 'IdentityUserClaims' and 'IdentityUserLogins'. It actually does what I want it to do within reason, the 'Id' in 'cvdetails' is set as a foreign key but of 'ApplicationUsers' which has exactly the same columns as 'AspNetUsers', the problem being all the user data is still storing in 'AspNetUsers' which is the table I want my 'CVDetails' model to link to.

    Any suggestions to how I can fix this?
  • #763948
    Hi

    What's your problem?
    Please elaborate your question first, so that people can understand and give their valuable suggestions for the same.

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #763949
    I'm trying to link 'ASPNetUsers' to my model 'CVDetails'. I'm attempting to reference the 'ID' from the former as a foreign key in 'CVDetails'.

    However, from the code above it's creating the ASPNetUser tables and then creating duplicates of those tables but named 'Identity....' instead.

    It's creating the relationship that I want, but to 'ApplicationUsers' which has exactly the same fields as 'ASPNetUsers' but without the data that I need.

    Delete Attachment

  • #763955
    Try to use the ASPNetUsers in your table.
    In following ex, At the time of registration I am adding that same id to our required table.

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
    if (ModelState.IsValid)
    {
    var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
    var result = await UserManager.CreateAsync(user, model.Password);
    if (result.Succeeded)
    {
    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
    Org_Profile hotel = new Org_Profile();
    hotel.Id = Guid.NewGuid();
    hotel.UserId = new Guid(user.Id);
    hotel.Name = "";
    ProfileRepository aHotelRepositoryL = new ProfileRepository();
    aHotelRepositoryL.Add(hotel);
    return RedirectToAction("Index", "Home");
    }
    AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
    }



    And also you can get the logged in users by using the User.Identity.GetUserId()

    By Nathan
    Direction is important than speed

  • #763961
    Where would I put that code?


Sign In to post your comments