【问题标题】:How to join my tables with identity tables?如何将我的表与身份表连接起来?
【发布时间】:2016-06-09 20:29:45
【问题描述】:

我使用 Identity 和 EF 启动了一个默认 MVC 项目。 在我的应用程序中,用户将能够创建和编辑一些记录。 在这些记录的表中,我想要创建记录和最后更新的用户的 ID。

我的模型类是这样的:

public class Record
{
    public int ID { get; set; }
    public DateTime CreateTime { get; set; }
    public string CreatingUserID { get; set; }
    public string UpdatingUserID { get; set; }
    public DateTime UpdateTime { get; set; }
    public Enums.RecordStatus Status { get; set; }
}

在 RecordsController 中,我将新记录保存到数据库,如下所示:

    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(FormCollection form, RecordCreateVM vm)
    {

        string userId = User.Identity.GetUserId();
        DateTime now = DateTime.Now;
        Record rec = new Record ();

        if (ModelState.IsValid)
        {
            int newRecordId;

            using (RecordRepository wr = new RecordRepository())
            {
                UpdateModel(rec);
                rec.CreateTime = now;
                rec.UpdateTime = now;
                rec.CreatingUserID = userId;
                rec.UpdatingUserID = userId;
                rec.Status = Enums.RecordStatus.Active;

                Record result = wr.Add(rec);
                wr.SaveChanges();
                newRecordId = result.ID;
            }
    }
}

当我列出这些记录时,我还希望我的页面显示这些用户的用户名。 我从我创建的存储库中获取所有活动记录。

    public ActionResult Index()
    {
        RecordListVMviewModel = new RecordListVM();
        using (RecordRepository wr = new (RecordRepository())
        {
            viewModel.Records = wr.GetAll();
        }
        return View(viewModel);
    }

这是存储库代码:

public class RecordRepository: Repository<Record>
{
    public override List<Record> GetAll()
    {
        IQueryable<Record> activeRecords = DbSet.Where(w => w.Status == Enums.RecordStatus.Active);
        return activeRecords.ToList();
    }      
}

我必须在哪里进行更改?你能给我一个这样的用法示例代码吗? 谢谢。

【问题讨论】:

  • 这是example。希望对你有帮助~~

标签: asp.net entity-framework identity


【解决方案1】:

你需要改变

public string CreatingUserID { get; set; }
public string UpdatingUserID { get; set; }

类似于:

public User CreatingUser { get; set; }
public User UpdatingUser { get; set; }

在创建 new RecordRepository() 期间设置 ID

然后以 Record.CreatingUser.FirstName 等方式访问它们

【讨论】:

  • 谢谢。我还尝试将导航属性添加到 Record 模型类,但在添加迁移时出现错误。但是在您回答之后,我坚持要这样做:) 因为我的 Record 和 Identity DbSet 位于不同的 DbContexts 中,所以在创建迁移时发生了错误。所以我删除了默认的 ApplicationDbContext,并让我的其他 DbContext 派生自 IdentityDbContext。但我将继续搜索加入来自不同 DbContexts 的两个 DbSet。我是 EntityFramework 的新手,我应该学习 :)
  • 只是为了节省您的时间,您不能从两个不同的 DbContext 加入 DbSet。从相同的上下文创建 DbSet。另一个提示 - 当您插入一条记录时,您需要刷新上下文/实体/导航属性才能访问 Object.Property 字段。看看这个例子:stackoverflow.com/questions/9081244/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 2020-12-29
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多