Entity Framework现有表列的外键

时间:2014-06-17 16:05:09

标签: entity-framework entity-framework-6

我的数据库中有以下表格

公司

  • resourceId(uniqueidentifier)
  • name(nvarchar(50))

我的应用程序中有以下用户实体

public class ApplicationUser : IdentityUser
{

    public String FirstName { get; set; }
    public String Surname { get; set; }
    public Guid CompanyId { get; set; }

}

和配置类

public class ApplicationUserMap : EntityTypeConfiguration<ApplicationUser>
{

    public ApplicationUserMap()
    {



    }

}

使用fluentapi如何将Application用户的CompanyId中的foriegn密钥映射到现有的表resourceid?

1 个答案:

答案 0 :(得分:1)

如果您的模型中未包含Company,则无法执行此操作。

您只能使用标准T-SQL句子,数据库初始化(Seed())或自定义迁移(如果您正在使用迁移)在数据库中创建关系。

这个命令就像这样:

alter table ApplicationUser
add constraint App_Company_FK FOREIGN KEY (CompanyId) references Company(CompanyId)

要在Seed方法中运行,请覆盖已插入的Seed()方法和use any of the overloads of Database.ExecuteSqlCommand

context.Database.ExecuteSqlCommand( ... );
相关问题