Reputation: 43
I have a Student
table wherein I find a record with primary key UserID
using Find
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();
}
My question is how do I find a record but cannot use his primary key? In my case my IndividualInventoryRecord
has primary key RecordID
. I want to find a record from this table using FK UserID
I have tried this but inventory
returns 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();
}
I also tried using SingleOrDefault()
Upvotes: 1
Views: 834
Reputation: 205939
Unfortunately Find
method is the only method which takes the local cache into account. All standard Queryable
methods are translated to SQL and executed in database, hence return only existing database table records.
However it's not that hard to write your own custom extension method similar to Find
but with predicate expression:
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);
}
}
and use it instead of FirstOrDefault
:
var inventory = db.IndividualInventoryRecords.FindFirst(e => e.UserID == currentUserId);
Upvotes: 2
Reputation: 13146
Because, you are not saving to database the userInv
instance. Just save it;
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);
Upvotes: 1