我有一个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()
答案 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);