1

I have a Model League, and the corresponsing SQL Server table has a DateCreated column that uses a default SQL value of getdate().

When I add a new League, the DateCreated column gets written with a null value, which I'm guessing is a result of the EF overwriting the SQL getdate() function. Is there a way to get the EF to ignore this column when adding a new row? Here's my create action:

    [HttpPost]
    public ActionResult Create(LeagueCreateViewModel lcv)
    {
        League league = new League();
        league.Title = lcv.Title;
        league.SiteId = lcv.SiteId;

        if (ModelState.IsValid)
        {
            db.Leagues.Add(league);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.SiteId = new SelectList(db.Sites, "Id", "Title", league.SiteId);
        return View(lcv);
    }
1
  • What happens if you change the DateCreatedColumn so it won't allow null values? Commented Apr 22, 2013 at 5:11

1 Answer 1

1

If you are using EF 4.1 then it's not supported and you have to be explicit about it - take care of that in code. What you an do is create a partial class for your object and do the "defaulting" in your object's constructor.

public partial class League {
    public League() {
        DateCreated = DateTime.Now; 
        // or DateTime.UtcNow, depends on your logic
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

OK thanks, I'll give that a try. One more thing - in the [HttpPost] Edit action, I won't want this property set or updated at all, so what would I do in that situation?
In EF 4.1, if you don't set that value that won't get updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.