2

I'm trying to save an object in my OODB, that is basically a news item (a title, some text, a poster and a postdate).

I have no trouble retrieving the user object from the ASP.NET MembershipUser class.

but when I try to save, it seems not all of the data is recorded in my database. Below is the create method code sample:

[HttpPost]
public ActionResult Create(Newsitem newsitem)
{
    if (ModelState.IsValid)
    {
        newsitem.postdate = DateTime.Now;
        newsitem.originalposter = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);

        db.newsitems.Add(newsitem);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }

    return View(newsitem);
}

For example when I load the object from my DB it lacks the username. This is my load method:

public ActionResult Index()
{
    var news = (from n in newsDB.newsitems orderby n.postdate descending select n).Take(10);
    return View(news);
}

Anybody know why some of the variables of the object is not saved?

theB
  • 6,450
  • 1
  • 28
  • 38
AronChan
  • 245
  • 3
  • 19
  • small unrelated tip: use DateTime.UtcNow instead of DateTime.Now. Will make your life much easier down the road. It is good practice to store all dates/times in UTC. ;-) – santiagoIT Nov 22 '11 at 14:57
  • How is Newsitem.originalposter defined? – santiagoIT Nov 22 '11 at 14:58
  • it is defined like this: public MembershipUser originalposter { get; set; } but the MembershipUser is a build in ASP.NET userclass which has some readonly attributes including username. perhaps this is why i cant save it. i dont know – AronChan Nov 22 '11 at 15:00

1 Answers1

1

Yes, it is best that you have defined originalposter as an GUID. If I remember correctly the default asp.net membership provider defines UserId's as Guid's. If you do that, it will work.

Then you can do as follows:

newsitem.originalposter = (Guid)Membership.GetUser().ProviderUserKey;
santiagoIT
  • 9,411
  • 6
  • 46
  • 57