Note that there are some explanatory texts on larger screens.

plurals
  1. POEF - altering FK relationships with Fluent Api without dropping DB?
    primarykey
    data
    text
    <p>I've run into the situation many times where I have to add or alter a FK relationship to a code-first migrated database. Take, for example, this model: </p> <pre><code>public sealed class Post : ITenantData { [Key] [Required] public int PostId { get; set; } public int TenantId { get; set; } } </code></pre> <p>In my <code>Tenant</code> <code>EntityTypeConfiguration</code>, I have the following: </p> <pre><code> HasMany(c =&gt; c.Posts) .WithRequired() .HasForeignKey(u =&gt; u.TenantId); </code></pre> <p>This is working as I'd expect - the <code>TenantId</code> column of <code>Posts</code> is used when I query <code>Tenant.Posts</code>. </p> <p>But now I want to add a virtual property from the <code>Post</code> to the <code>Tenant</code>, altering the above model to the following: </p> <pre><code>public sealed class Post : ITenantData { [Key] [Required] public int PostId { get; set; } public int TenantId { get; set; } public virtual Tenant {get; set; } } </code></pre> <p>I update the <code>Post</code> <code>EntityTypeConfiguration</code>:</p> <pre><code> HasRequired(c =&gt; c.Tenant) .WithMany() .HasForeignKey(u =&gt; u.TenantId); </code></pre> <p>And hit <code>update-database</code>. I get an error: </p> <blockquote> <p>The operation failed because an index or statistics with name 'IX_TenantId' already exists on table 'dbo.Post'.</p> </blockquote> <p>In the output, I see this (among other things): </p> <pre><code> CREATE INDEX [IX_TenantId] ON [dbo].[Post]([TenantId]) </code></pre> <p>Followed by the stacktrace. This isn't a huge deal right now because the app is in development and I can just kill the db. Obviously I can't do that in production. How can I perform this simple change via migrations without dropping the db?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload