Get Latest record of table via Entity Framework

asp.net-mvc entity-framework

Question

I'm using code first feature of EntityFramework and I have created a model class with this field that have their own property (I don't mention them here!) :

public class Portrait
{
        private Guid _id;
        private string _aboutimage;
        private string _aboutMe;
        private string _mainMenu;
        private string _headerImage;
        private string _resume;
        private string _showpiece;
        private string _siteMenu;
        private string _adminMenu;
}

and for each part of this class I have separate ViewModel, for example I have AboutViewModel to update About in admin part and navigate in about page in website :

public class AboutViewModel
{
        public Guid Id { get; set; }
        public string AboutText { get; set; }
        public string Image { get; set; }
}

Now when I update the AboutViewModel, Portrait table in database will create a record that will have about text (other field will be null)

And for updating for other part of this table like Resume or others, it will generate another record with updated and inserted field (now in this record about text will be null!)

Now how can I get the about field to show it in UI as I have several records !? I don't want and also can not get these field by ID because I always want to have their latest updated to show in web site, what I have written is like this ,my about action to get the about text is like this :

public ViewResult About()
{
            var about= _portraitRepository.GetContent();

            return View(about);
}

and the GetContent() is like this :

public Portrait GetContent()
{
            return _siteContext.Portraits.Find();
}

but dosn't work and I got this error:

The number of primary key values passed must match number of primary key values defined on the entity. Parameter name: keyValues

Am I in a wrong direction? How can I solve this problem please?

1
1
2/12/2013 12:26:16 PM

Popular Answer

Another option is to get the Max value of the Id of Portrait table if it is an identity column.

The action will look like below.

public ActionResult About()
{
    var about= _portraitRepository.GetLatest();
}

Repository will look like below.

public Portrait GetLatest()
{
    var latestId = _siteContext.Portraits.Max(p => p.Id);
    return _siteContext.Portraits.Find(latestId);
}
6
2/13/2013 9:14:51 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow