【问题标题】:Mvc identity: Adding UserId to another tableMvc 身份:将 UserId 添加到另一个表
【发布时间】:2016-08-11 08:40:39
【问题描述】:

我有一个模型叫 Sammanhang

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

public string Namn { get; set; }

我想将用户的 id 作为外键包含在内,这样我就可以获得数据库中所有用户的下拉列表。

我尝试做这样的事情

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

在 IdentityModels 内部

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

但是没有成功,请问有没有办法实现用户下拉列表?

【问题讨论】:

  • But without no success - 请详细说明并具体说明。
  • 当我尝试在包管理器中“添加迁移”和“更新数据库”时,我得到:“无法确定类型‘IdentitySample.Models.ApplicationUser’之间关联的主体端”和“Checkin.Models.Sammanhang”。必须使用关系流式 API 或数据注释显式配置此关联的主体端。”
  • 你的外键注释 UserId 应该在你的 UserId 属性之上。

标签: c# asp.net-mvc asp.net-identity dropdown


【解决方案1】:

您好,您解决了这个问题吗? 我也经历过,改变了

public virtual ApplicationUser ApplicationUser { get; set; }

public virtual IdentityUser IdentityUser { get; set; }

解决了我的问题(至少它通过了迁移并且在 Edmx 中正确建立了关系) 我认为这不是正确的技术,所以如果你完成了请告诉我

【讨论】:

    【解决方案2】:

    如果需要快速设置,请尝试使用 SelectListItem 和匿名类型。

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

    或使用现有模型,

    @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>
    

    更多信息请访问:http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多