建模一对多关系-模型与视图模型 [英] Modeling a one-to many relationship- Model vs ViewModel

查看:64
本文介绍了建模一对多关系-模型与视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试对与Model-First MVC中的另一个对象具有一对多关系的对象类进行建模-一个联系"对象,该对象除其他外还包括(引用?)一个对象的列表.或更多兴趣",是从完整的兴趣数据库列表中创建联系人时选择的.据我了解,人们使用ViewModel来容纳这种关系,但是我认为我误解了模型与viewModel的关系.

I am currently trying to model an object class with a one-to-many relationship with another object in Model-First MVC- a "Contact" object that includes, among other things, a list of (references to?) one or more "Interests", chosen upon creation of a Contact from the full database list of Interests. It is my understanding that one uses a ViewModel to accommodate such a relationship, but I think I am misunderstanding what does or does not go in the model vs the viewModel.

目前,我有一个通讯录模型:

At present, I have a Contacts model:

public class Contact
{
    public int Id { get; set; }

    public string Email { get; set; }

    public virtual List<Interest> Interests { get; set; }

    public List<int> InterestIds { get; set; }
}

兴趣模型:

public class Interest
{
    public int Id { get; set; }

    public string Name { get; set; }
}

联系人视图模型:

public class ContactViewModel
{
    public int Id { get; set; }

    public string Email { get; set; }

    public List<int> InterestIds { get; set; }

    public List<InterestViewModel> Interests { get; set; }
}

还有一个兴趣视图模型

public class ContactViewModel
{
    public int Id { get; set; }

    public string Email { get; set; }

    public List<int> InterestIds { get; set; }

    public List<InterestViewModel> Interests { get; set; }
}

但我对去往何处的说法有所矛盾.

But I'm getting conflicted accounts of what goes where.

简而言之,我希望最终结果是我应该能够从创建"视图中选择一个或多个兴趣(最好带有一系列复选框)以存储在新联系人中,然后从索引"视图中进行选择筛选联系人列表,根据该列表他们有或没有兴趣.我已经为其中的大多数计划了逻辑,但是目前我应该如何设计我的模型与我的ViewModel,以最好地适应这种愿景?

In short, I intend the end result that I should be able to choose one or more Interests (preferably with a series of checkboxes) from the Create view to be stored in the new Contact, and then from the Index view be able to filter the table of Contacts by which Interests they do or do not have. I have logic planned out for most of that already, but for the time being how should I design my Models vs my ViewModels in order to best accommodate this vision?

推荐答案

您的 Contact 实体存在逻辑错误,应从 Contact 实体,然后将名称为 ContactId 的属性添加到您的 Interest 实体.它为联系人提供外键(从 Contact Interest 的一对多关系).但是,如果ViewModel等于Model,则不需要任何ViewModel.

your Contact entity has a logical error, you should remove InterestIds property from Contact entity and add a property with name ContactId to your Interest entity. it provides foreign key for contact(one to many relation from Contact to Interest). however if ViewModel is equals to the Model, so you don't need any ViewModel.

这篇关于建模一对多关系-模型与视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆