具有多个表的实体框架ViewModel

时间:2014-07-30 22:12:15

标签: asp.net-mvc entity-framework

我正在为Events表构建MVC CRUD页面,其中我在表(C)DeviceChannel和表(D)事件之间有一对多。表(C)由表(A)设备和(B)信道的2个外键描述。还有一个外键来描述EventType。

DeviceChannel没有描述(因此我不能将其用作直接查找事件),尽管它确实有与之关联的各种值,因此我必须包含Device和Channel表。

我已经使用上面的表构建了一个ViewModel但是当我尝试创建一个Controller时,我得到的错误是抱怨ViewModel没有元数据。表之间没有定义键。所有表都有密钥并在EF数据库中正确加载。

我正在使用VS2013和.Net 4.5.2 我在遵循NerdDinners示例后尝试使用存储库,但没有成功。 的的问题: 我是否应该使用ViewModel来开发此解决方案。 如果我使用ViewModel,如何在尝试scafold控制器时解决元数据/密钥问题?

1 个答案:

答案 0 :(得分:0)

我通过简化ViewModel解决了这个问题。

public class DeviceChannelEventsViewModel
{
    public SelectList eventType { get; private set; } 
    public SelectList deviceChannel { get; private set; }
    public CRHSEvent crhsEvent { get; set; }
    public DeviceChannelEventsViewModel(SelectList _deviceChannel, SelectList _eventType, CRHSEvent _crhsEvent)
    {
        deviceChannel = _deviceChannel;
        eventType = _eventType;
        crhsEvent = _crhsEvent;
    }
    public DeviceChannelEventsViewModel(SelectList _deviceChannel, SelectList _eventType)
    {
        deviceChannel = _deviceChannel;
        eventType = _eventType;
        crhsEvent = new CRHSEvent();
    }
}

当我为deviceChannel创建选择列表时,我将Device和Channel表加入了devicechannel表:

DeviceChannelRepository dcr = new DeviceChannelRepository();
IEnumerable<DeviceChannel> dc = dcr.FindAllDeviceChannelsDescribed(); 
SelectList deviceChannels = new SelectList(dc.Select(s => new 
{ 
    DeviceChannelID = s.DeviceChannelID ,
    DCDescription=string.Format("{0} | {1}",s.Device.DeviceName,s.Channel.Description)
}).ToList(), "DeviceChannelID", "DCDescription");

SelectList eventType = new SelectList(db.EventType, "EventTypeID", "Description");
DeviceChannelEventsViewModel dCEViewModel = 
new DeviceChannelEventsViewModel(deviceChannels, eventType);