如何更新与EF映射的一对多关系中的外键?

时间:2017-01-07 22:02:14

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

我使用EF约定创建了一对多的关系。然后在update-databaseCompany_CompanyId表中的WorkRoles列后,这是所需的结果。

但是当我尝试使用这个外键时,我可以将不同的角色与我遇到的不同公司联系起来。

在我的WorkRoleController中,我希望能够以我访问其他属性的方式访问FK属性,但事实并非如此。

当我输入workrole(dot)时,我看到了RoleNameRoleDescriptionWorkRoleId,而不是Company_CompanyId,我只看到Company。哪个是对象Company,而不是外键。

所以我的问题是,如何使用该外键,因此在创建新角色时我可以执行以下操作:

Company company = db.Companies.Where(c => c.CAId == currentUserId)
                              .FirstOrDefault();

int companyID = company.CompanyId;    // find the company for the current user

workRole.Company_CompanyId = companyID;    // save the company ID to the FK field.

有人可以帮忙吗?保存workrole时如何实际保存外键?

角色模型:

public class WorkRole
{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int WorkRoleId { get; set; }
        public string RoleName { get; set; }
        public string RoleDescription { get; set; }
        public virtual Company Company { get; set; }
}

公司型号:

public class Company
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CompanyId { get; set; }
    public byte[] ImageData { get; set; }
    [NotMapped]
    public HttpPostedFileBase UploadImage { get; set; }
    [NotMapped]
    public string ImageBase64 => System.Convert.ToBase64String(ImageData);
    public string CompanyName { get; set; }
    public string CAId { get; set; }
    public virtual ICollection<WorkRole> WorkRoles { get; set; }
}

1 个答案:

答案 0 :(得分:2)

CompanyId属性添加到WorkRole类,将更改推送到数据库,然后在键入workrole(dot)时看到它并根据需要更新它。

public class WorkRole
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int WorkRoleId { get; set; }
        public string RoleName { get; set; }
        public string RoleDescription { get; set; }
        public int CompanyId {get; set;}// this will be mapped as foreign key by EF convention.
        public virtual Company Company { get; set; }
    }

如果您的外键属性名称不遵循任何EF约定,则可以使用[ForeignKey]数据注释让EF知道您刚定义的属性实际上是外键:

public class WorkRole
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int WorkRoleId { get; set; }
        public string RoleName { get; set; }
        public string RoleDescription { get; set; }
        [ForeignKey("Company")]
        public int Foo {get; set;}
        public virtual Company Company { get; set; }
    }

您也可以在导航属性中使用它:

public class WorkRole
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int WorkRoleId { get; set; }
        public string RoleName { get; set; }
        public string RoleDescription { get; set; }
        public int Foo {get; set;}
        [ForeignKey("Foo")]
        public virtual Company Company { get; set; }
    }