4

I have a Model called Sammanhang

[Key]
public int SammanhangsID { get; set; }

public string Namn { get; set; }

And I want to include the id of the users as a foreign key so that i can get a dropdown-list of all the users in the database.

I attepmted doing something like this

public class Sammanhang
{
    [Key]
    public int SammanhangsID { get; set; }

    public string Namn { get; set; }

    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public virtual ApplicationUser ApplicationUser { get; set; }
}

and inside IdentityModels

public class ApplicationUser : IdentityUser
{
    public virtual Sammanhang Sammanhang { get; set; }
}

But without no success, Is there anyway to achieve a user dropdownlist?

  • 1
    `But without no success` - please elaborate and be specific. – Igor Apr 19 '16 at 09:37
  • When I try to "add-migration" and then "update-database" in package manager I get: "Unable to determine the principal end of an association between the types 'IdentitySample.Models.ApplicationUser' and 'Checkin.Models.Sammanhang'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations." – Filip Pettersson Apr 19 '16 at 10:14
  • Your foreign key annotation UserId should be above your UserId property. – David B Sep 13 '17 at 11:41

2 Answers2

0

Hi Have you solved this problem? I had been through this also and changed

public virtual ApplicationUser ApplicationUser { get; set; }

to

public virtual IdentityUser IdentityUser { get; set; }

solved my issue (at least it passed the migration and the relationship was build correctly in Edmx) I believe this was not proper technique, so please let me know if you got this done

RizkiDPrast
  • 1,695
  • 1
  • 14
  • 21
0

Try using a SelectListItem and anonymous types if something needs to be setup quickly.

  @Html.DropDownList("Users", new List<SelectListItem>
{
new SelectListItem { Text = "John" },
new SelectListItem { Text = "Frank" },
new SelectListItem { Text = "Joe" }
}, "Select User")

Or using an existing Model,

@using (Html.BeginForm()) {

    <fieldset>

        <legend>Select Users</legend>

        <div class="editor-field">

            @Html.ListBox("Users", ViewBag.Userslist as MultiSelectList

            )

        </div>

        <p>

            <input type="submit" value="Save" />

        </p>

    </fieldset>

More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

JDavila
  • 409
  • 1
  • 7
  • 22