C#LINQ查询创建意外的新行

时间:2015-01-06 08:35:06

标签: c# linq

我有以下函数,根据给定的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;
}

1 个答案:

答案 0 :(得分:4)

您的school来自不同的CloudPrintDbContext,因此db语句中的using实例无法跟踪它。如果它没有附加到任何其他DbContext,那么您可以在设置School之前将其附加到该db.Schools.Attach(school); ,然后它应该可以正常工作。

DbSet.Create()

除此之外,我建议您使用new方法而不是{{1}},以便按照EF documentation使用动态代理。