将CheckBoxFor与SQL查找表一起使用

时间:2015-12-18 19:06:36

标签: c# entity-framework asp.net-mvc-4 razor checkboxfor

我是MVC新手,我正在尝试为我的数据创建一个Checkbox列表。我有3张桌子:

CREATE TABLE [dbo].[Competency] (
    [Id]           INT          IDENTITY (1, 1) NOT NULL,
    [Icon]         VARCHAR (5)  NOT NULL,
    [Description]  VARCHAR (50),
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[User] (
    [Id]           INT          IDENTITY (1, 1) NOT NULL,
    [Name]         VARCHAR (50)  NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[UserCompetency] (
    [UserId]       INT NOT NULL,
    [CompetencyId] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([UserId] ASC, [CompetencyId] ASC),
    CONSTRAINT [FK_UserCompetency_ToCompetency] FOREIGN KEY ([CompetencyId]) REFERENCES [dbo].[Competency] ([Id]),
    CONSTRAINT [FK_UserCompetency_ToUser] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([Id])
);

所以我有一份能力和用户列表,每个用户可以拥有零或多个这些能力。

EntityFramework创建了我的User类,如下所示:

public partial class User
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public User()
    {
        this.Competencies = new HashSet<Competency>();
    }

    public int Id { get; set; }
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Competency> Competencies { get; set; }
}

在MVC和Razor中,我正在尝试创建一个CheckBoxList,以便用户可以选择与每个用户一起使用的能力。用户Create.cshtml包含以下代码:

@foreach(Competency comp in Competencies)
{
    @Html.CheckBoxFor(model => model.Competencies.Contains(comp))
    @Html.DisplayFor(model => comp.Icon, new { Title = comp.Description })
}

我收到错误:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

在CheckBoxFor的行上。

据我所知,使用CheckboxFor应该链接到模型中的布尔字段,这是我没有的,因为这是从查找表中获取数据。

我想避免更改EntityFramework创建的模型,因为每当它更新时,我都要记得重新进行更改。

有人知道如何在引用不涉及修改模型的查找表时让CheckBoxFor工作吗?

0 个答案:

没有答案