我有以下函数,根据给定的mac地址是否存在,创建新行或更新模型MACReg
中的现有行。
public Boolean RegisterMAC(string pwd, string mac, string location)
{
School school = getSchoolByCode(pwd);
if (school == null)
{
return false;
}
//initial register or update
using (CloudPrintDbContext db = new CloudPrintDbContext())
{
MACReg r = db.MACRegs.Find(mac);
if (r == null) //create new row
{
MACReg m = new MACReg { MAC = mac, Location = location,
School = school, RegTime = DateTime.Now, UpdateTime = DateTime.Now };
db.MACRegs.Add(m);
}
else //update location
{
r.School = school;
r.Location = location;
r.UpdateTime = DateTime.Now;
}
db.SaveChanges();
}
return true;
}
然而,问题是它总是在模型School
(而不是MACReg
)中创建一个新行。知道为什么吗?谢谢!
MACReg和School的模型如下:
public class MACReg
{
[Key]
public string MAC { set; get; }
[Required]
public School School { set; get; }
[Required]
public string Location { set; get; }
[Required]
public DateTime UpdateTime { set; get; }
[Required]
public DateTime RegTime { set; get; }
}
public class School
{
[Key]
public int SchoolID { set; get; }
[Required]
public string SchoolName { set; get; }
[Required]
public DateTime CreateTime { set; get; }
[Required]
public DateTime PwdExprTime { set; get; }
[Required]
public byte[] PwdHash { set; get; }
[Required]
public byte[] Salt { set; get; }
}
更新:getSchoolByCode低于
private School getSchoolByCode(string pwd)
{
using (CloudPrintDbContext db = new CloudPrintDbContext())
{
foreach(School s in db.Schools.Where(s => s.PwdExprTime > DateTime.Now)){
byte[] userH = HashUtils.GenerateHash_Salt(pwd, s.Salt);
if (HashUtils.CompareByteArrays(userH, s.PwdHash))
{
return s;
}
}
}
return null;
}
答案 0 :(得分:4)
您的school
来自不同的CloudPrintDbContext
,因此db
语句中的using
实例无法跟踪它。如果它没有附加到任何其他DbContext
,那么您可以在设置School
之前将其附加到该db.Schools.Attach(school);
,然后它应该可以正常工作。
DbSet.Create()
除此之外,我建议您使用new
方法而不是{{1}},以便按照EF documentation使用动态代理。