1

我正在使用 EntityFramework 的代码优先功能,并且我创建了一个模型类,该字段具有自己的属性(我在这里没有提到它们!):

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;
}

对于此类的每个部分,我都有单独的 ViewModel,例如,我必须在管理部分AboutViewModel进行更新About并在网站的 about 页面中导航:

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

现在,当我更新数据库中的AboutViewModelPortrait时,将创建一条包含关于文本的记录(其他字段将为空)

并且为了更新该表的其他部分Resume或其他部分,它将生成另一条具有更新和插入字段的记录(现在在此记录中关于文本的内容将为空!)

现在我怎样才能让 about 字段在 UI 中显示它,因为我有几条记录!?我不想也不能通过 ID 获取这些字段,因为我总是希望他们的最新更新显示在网站上,我写的是这样的,我获取 about 文本的操作是这样的:

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

            return View(about);
}

GetContent()这样的:

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

但不起作用,我收到了这个错误:

传递的主键值的数量必须与实体上定义的主键值的数量相匹配。参数名称:keyValues

我走错方向了吗?请问我该如何解决这个问题?

4

3 回答 3

7

另一种选择是获取Portrait 表的Id的最大值(如果它是一个标识列)。

操作将如下所示。

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

存储库将如下所示。

public Portrait GetLatest()
{
    var latestId = _siteContext.Portraits.Max(p => p.Id);
    return _siteContext.Portraits.Find(latestId);
}
于 2013-02-12T18:31:05.020 回答
1

You should retrieve the ID when you perform the insert. Then save that value to Session or something for later use in your About Action

The call to the repository to persom the insert will look like below.

Session["LatestPortraitId"] = _portraitRepository.AddPortrait();

The method in the Portrait repository used to insert a new Portrait should look like below.

public int AddPortrait(portrait)
{
    _siteContext.AddObject(portrait);
    _siteContext.SaveChanges();
    return portrait.Id;
}

The About action will look like below.

public ActionResult About()
{
    var latestPortraitId = Int.Parse(Session["LatestPortraitId"]); 
    var about= _portraitRepository.GetContent(latestPortraitId);
}

Inside the repository it should be as shown below.

public Portrait GetContent(int id)
{
    return _siteContext.Portraits.Find(id);
}
于 2013-02-12T12:37:13.703 回答
0

按后代 ID 排序搜索,然后使用第一个属性

于 2017-04-23T13:57:00.230 回答