Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

c# - DateTime in the transfer parameter of the edit method in the controller is always 01.01.0001 00:00:00 asp.net mvc5

I a problem in the transfer parameter in the Edit Method "issue".

In Issue the CreatedDate and UpdatedDate is always {01.01.0001 00:00:00}.

The parameter Id, Title and Description is always correct.

My Controller:

public ActionResult Edit([Bind(Include = "Id,Title,Description")] Issue issue)
{
    if (ModelState.IsValid)
    {
        db.Entry(issue).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(issue);
}

My Model:

public class Issue : BaseEntity
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Required")]
    public string Title { get; set; }
    
    [AllowHtml]
    [Required(ErrorMessage = "Required")]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }

}

public class BaseEntity
{
    public DateTime CreatedDate { get; set; }
    public DateTime UpdatedDate { get; set; }
}

I can unfortunately can not debug from where the "issue" parameter comes from.

From where the transfer parameter "Issue issue" in the Edit method comes from and why are all DateTimes always {01.01.0001 00:00:00}?

When I create the first time a issue entity I add the DateTimme in the SaveChanges() Method with the following modification in my DBContext:

public override int SaveChanges()
{
    var entries = ChangeTracker
        .Entries()
        .Where(e => e.Entity is BaseEntity && (
                e.State == EntityState.Added
                || e.State == EntityState.Modified));

    foreach (var entityEntry in entries)
    {
        ((BaseEntity)entityEntry.Entity).UpdatedDate = DateTime.UtcNow;

        if (entityEntry.State == EntityState.Added)
        {
            ((BaseEntity)entityEntry.Entity).CreatedDate = DateTime.UtcNow;
        }
    }

    return base.SaveChanges();
}

And the SaveChanges() works without problem. When I create the issue entity the first time the DateTime has the correct value and I can also see it in the Detail View.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change your edit code to this

var exist =  d.Set<Issue>().FindAsync(issue.Id);
 
if (exist == null)
                {
//ErrorMessage = "Can't find item to update";
                    
}
else{

    db.Entry(exist).CurrentValues.SetValues(issue);
    var result = await db.SaveChanges(); // result should be  > 0
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...