dlimes
dlimes

Reputation: 105

How to use custom property name for foreign key column in Entity Framework

I for some reason cannot seem to find this info anywhere, but feel this would be a common thing. I originally had this class:

public class SiteSharingPermission
{
    [Required]
    public Guid Id { get; set; }

    public Guid OrganizationId { get; set; }
    public Organization Organization { get; set; }
}

I recently needed to modify this column / property (OrganizationId -> PartnerOrganizationId) but I'm having an issue with my migrations on updating the foreign key column property name.

I tried running migrations, modified the up/down to this:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_SiteSharingPermissions_Organizations_OrganizationId",
            table: "SiteSharingPermissions");

        migrationBuilder.RenameColumn(
            name: "OrganizationId",
            table: "SiteSharingPermissions",
            newName: "PartnerOrganizationId");

        migrationBuilder.AddForeignKey(
            name: "FK_SiteSharingPermissions_Organizations_PartnerOrganizationId",
            table: "SiteSharingPermissions",
            column: "PartnerOrganizationId",
            principalTable: "Organizations",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_SiteSharingPermissions_Organizations_PartnerOrganizationId",
            table: "SiteSharingPermissions");

        migrationBuilder.RenameColumn(
            name: "PartnerOrganizationId",
            table: "SiteSharingPermissions",
            newName: "OrganizationId");

        migrationBuilder.AddForeignKey(
            name: "FK_SiteSharingPermissions_Organizations_OrganizationId",
            table: "SiteSharingPermissions",
            column: "OrganizationId",
            principalTable: "Organizations",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
    }

But I keep getting an error when trying to get results from this table:

Unknown column 's.OrganizationId' in field list

Any ideas?

Upvotes: 0

Views: 1233

Answers (1)

Akash Veer
Akash Veer

Reputation: 180

I personally won't prefer making changes to migration file. Instead do something like below.

public class SiteSharingPermission
{
   [Required]
   public Guid Id { get; set; }

   public Guid PartnerOrganizationId { get; set; }
   [ForeignKey("PartnerOrganizationId")]
   public Organization Organization { get; set; }
}

You can also do it using Fluent API method.

Upvotes: 2

Related Questions