在没有主键的情况下在dbset中查找记录

时间:2017-12-19 17:36:21

标签: c# entity-framework

我有一个Student表,其中我使用查找

找到主键UserID的记录
        var currentUserId = User.Identity.GetUserId();
        var newid = db.Students.FirstOrDefault(d => d.UserID == currentUserId);

        if (newid == null)
        {
            newid = db.Students.Create();
            newid.UserID = currentUserId;
            db.Students.Add(newid);

        }

        Student student = db.Students.Find(newid.UserID);
        if (student == null)
        {
            return HttpNotFound();
        }

我的问题是如何查找记录但不能使用他的主键?就我而言,我的IndividualInventoryRecord有主键RecordID。我想使用FK UserID

从此表中找到记录

我试过了,但inventory返回null

var userInv = db.IndividualInventoryRecords.FirstOrDefault(d => d.UserID == currentUserId);

        if (userInv == null)
        {
            userInv = db.IndividualInventoryRecords.Create();
            userInv.UserID = currentUserId;
            db.IndividualInventoryRecords.Add(userInv);
        }

        IndividualInventoryRecord inventory = db.IndividualInventoryRecords.FirstOrDefault(user => user.UserID == currentUserId);

        if (inventory == null)
        {
            return HttpNotFound();
        }

我也尝试过使用SingleOrDefault()

2 个答案:

答案 0 :(得分:2)

不幸的是,Find方法是考虑本地缓存的唯一方法。所有标准Queryable方法都转换为SQL并在数据库中执行,因此只返回现有的数据库表记录。

然而,使用类似于Find但使用谓词表达式编写自己的自定义扩展方法并不困难:

public static partial class DbSetExtensions
{
    public static T FindFirst<T>(this DbSet<T> source, Expression<Func<T, bool>> predicate)
        where T : class
    {
        return source.Local.AsQueryable().FirstOrDefault(predicate) ?? source.FirstOrDefault(predicate);
    }
}

并使用它代替FirstOrDefault

var inventory = db.IndividualInventoryRecords.FindFirst(e => e.UserID == currentUserId);

答案 1 :(得分:1)

因为您没有将userInv实例保存到数据库。保存吧;

    if (userInv == null)
    {
        userInv = db.IndividualInventoryRecords.Create();
        userInv.UserID = currentUserId;
        db.IndividualInventoryRecords.Add(userInv);
        db.SaveChanges();
    }
    IndividualInventoryRecord inventory = db.IndividualInventoryRecords.FirstOrDefault(user => user.UserID == currentUserId);