使用EF和Linq从数据库检索数据时访问Identity用户的其他属性

时间:2016-02-28 07:07:40

标签: c# asp.net asp.net-mvc asp.net-identity entity-framework-core

假设我在使用asp.net标识时向默认用户添加了一些其他属性:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我知道在我的asp.net MVC控制器中我可以简单地执行以下操作来获取当前登录用户的名字:

User.Identity.Name

因此,当保存到数据库时,我可以简单地将User.Identity.Name与我保存的对象一起传递到我的存储库,以便可以填充CreatedBy字段。

现在假设我正在从数据库中检索具有CreatedBy字段的项目,该字段包含用户名的字符串,但我想在视图中显示Created by:FirstName + LastName。

我如何获得这些额外信息?如果我使用纯SQL,我会在AspNetUsers表上进行INNER JOIN,其中CreatedBy = Username,只需在名为CreatedByFullName的自定义列中检索FirstName和LastName。

由于我现在使用Entity Framework以及最新版本的ASP.NET Identity,我对如何检索用户信息以显示在我们的页面视图中感到困惑。是在我的存储库中使用linq进行连接还是只是将一个对象添加到我的每个名为ApplicationUser的属性中,还是有更好的方法?

2 个答案:

答案 0 :(得分:2)

假设:

  • 您有一个名为ApplicationUser的表格,其中包含您的所有用户。
  • 此表有一个Id列(int),您可以重用它来在其他表中存储查找。

其他类(我称之为单向导航属性):

public class BookContext : DbContext
{
    public DbSet<Book> Books { get; set; }
    public Dbset<ApplicationUser> Users { get; set; }

    public overridee OnModelCreating(DbModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Book>()
        .HasRequired(b => b.CreatedByUser)
        .WithMany()
        .HasForeignKey(b => b.CreatedBy);
    }
}

public class Book
{
  public int CreatedBy { get; set; }
  public virtual ApplicationUser CreatedByUser { get; set; }
}

然后你就是

using (var bookContext = new BookContext())
{
  var firstBookWithRelatedUser bookContext.Books
    .Include(b => b.CreatedByUser)
    .First();
}

这样的事情。我建议阅读Entity Framework Documentation。在上面的代码中,我几乎只是写下了我的头脑,所以我可能不完全正确。

如果您愿意,我称之为双向导航属性:

public class ApplicationUser : IdentityUser
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public ICollection<Book> Books { get; set; }
}

然后

    public overridee OnModelCreating(DbModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Book>()
        .HasRequired(b => b.CreatedByUser)
        .WithMany(u => u.Books)
        .HasForeignKey(b => b.CreatedBy);
    }

然后你就是

using (var bookContext = new BookContext())
{
  var firstUserWithAllRelatedBooks = bookContext.Users
    .Include(u => u.Books)
    .First();
}

这实际上取决于您的需求。但是,你可以最终得到一个了解所有关系的巨人God DbContext ......

答案 1 :(得分:0)

示例EF查询将如下所示 -

var result = (from tab in db.YourTable
            join user in db.AspNetUsers on user.username equals tab.CreatedBy                
            select new {YourTableObj = tab, CreatedByFullName = user.FirstName + " " + user.LastName).ToList();