2

I am new to MVC and I am trying to make a Checkbox List for my data. I have 3 tables:

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])
);

So I have a list of Competencies and Users, and each User could have zero or more of these Competencies.

EntityFramework created my User class as follows:

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

In MVC and Razor, I am trying to make a CheckBoxList so that the user can pick and choose which competencies go with each user. The User Create.cshtml contains this code:

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

I am getting the error:

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

on the line with the CheckBoxFor.

I understand that using the CheckboxFor should be linked to a Boolean field in the model, which I do not have since this is getting data from a lookup table.

I would like to avoid changing the model created by the EntityFramework because then whenever it gets updated, I would have to remember to re-make the change.

Does anyone know how I can get the CheckBoxFor to work when referencing a lookup table that does not involve modifying my model?

4

0 回答 0