附加了实体对象的DbContext传入param丢失的数据

时间:2015-03-20 11:19:39

标签: c# asp.net-mvc linq entity-framework

我有一个神秘的问题。

我使用Linq to Entities获取用户配置文件并将结果对象发送到函数以用MVC模型数据填充它。

using (var db = new DatabaseEntities())
{
    try
    {
        var user = db.Users.Single(u => u.Id == accorJobPrincipal.Id);
        //At the point, user.CreatedAt contains the right date
        user = model.GetBaseObject(user);
        //At the point, user.CreatedAt is equal to DateTime.MinValue (0001/01/01)

        user.UpdatedAt = DateTime.Now;

        db.SaveChanges(); //Here, I have an exception due to Overflow in SQL Datetime convert
    }
    catch (Exception ex)
    {
        ModelState.AddModelError(string.Empty, "A system error occured, please try later.");
    }
}

为什么实体对象在作为参数传递时会丢失数据?


编辑请在此处找到GetBaseObject()

的代码
public override Users GetBaseObject(Users objectFromContext = default(Users))
    {
        var returnUser = objectFromContext ?? new Users();

        returnUser.FirstName = FirstName;
        returnUser.LastName = LastName;
        returnUser.IdTitle = IdTitle;
        returnUser.CreatedAt = CreatedAt;
        returnUser.UpdatedAt = UpdatedAt;
        returnUser.DeletedAt = DeletedAt;
        returnUser.LastConnectionAt = LastConnectionAt;
        returnUser.Enabled = Enabled;
        returnUser.Email = Email;
        returnUser.NTLogin = NTLogin;
        returnUser.Login = Login;
        returnUser.Password = Password;
        returnUser.PasswordAttemptFailCount = PasswordAttemptFailCount;

        return returnUser;
    }

1 个答案:

答案 0 :(得分:0)

对不起,我发现我的noob错误发布了代码: - (

我在GetBaseObject()....

中重写了日期的值

在这里发布代码很有用^^你很好地看到错误。比我的Visual Studio更好:每次我都用过的.P。

感谢您的参与