简体   繁体   中英

MVC linking two tables by a string key rather than an int key

I'm using an intranet application - so Windows authentication.

The Username has the format "ADHP\\BCOOPER" - I would like the users to be able to show a "friendly name" when logged in, so want to map the Post -> UserName property, which is a string, to the CorpUsers -> UserName property, so I can then link the tables in my Linq Query, using .Include(x => x.CorpUsers)

How do you link two tables like this (when it's not the ID's/int's, and a string instead)?

These are the Domain Models I have just now:

public class Post
{
    public int PostId { get; set; }
    public string Content { get; set; }
    public string UserName { get; set; }
    public DateTime DateOfPost { get; set; 
}

public class CorpUsers
{
    public int CorpUsersId { get; set; }
    public string UserName { get; set; }
    public string FriendlyName { get; set; }

}

Thank you

It's hard to tell what you want here. Ie an MVC mapping or the LINQ join.

In LINQ you can do this:

var Posts = (from cu in ListCorpUsers
             join p in ListPosts on cu.UserName equals p.UserName
             select new {
                 FriendlyName = cu.FriendlyName,
                 UserName = cu.UserName,
                 Content = p.Content
             }).ToList();

This has nothing to do with whether you're dealing with ints or strings, but rather what is and is not a key on your table. If you want the foreign key to be the username in the related table, then the username must be your primary key on your user table. That's how database relationships work. However, I would not recommend at all actually making the username your primary key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM