주어진 MAC 주소의 존재 여부에 따라 새 행을 만들거나 MACReg
모델의 기존 행을 업데이트하는 follow 함수가 있습니다.C# LINQ 쿼리가 의도하지 않은 새 행을 만듭니다.
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과 학교에 대한
모델은 다음과 같습니다 :
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; }
}
UPDATE : 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;
}
디버깅하는 경우 r의 값은 무엇입니까? –
'학교'는 어디에서 왔습니까? 'db' 컨텍스트의 범위 밖에서 올 수있는 것처럼 보입니다. 또한 LINQ와 관련이 없습니다 (지금까지). – Rawling
@ L-Three r은 Mac이있을 때 db의 행을 나타내는 객체입니다. – totoro