1

Say I have an entity class A that uses a surrogate key for its PK and defines a uniqueness constraint that involves an FK into a different entity class B. All is well and good. However, somewhere down the line, I discover that my entity class A is actually defined by a subset of the key columns of B, rather than all of B's key columns.

So essentially, the scenario is: I want to add some columns and populate them with values computed by existing data in old columns and relationships before removing the old columns.

On the surface, this seems easy--I make the changes to my data model, add a new migration, and then use calls to Sql() with the T-Sql needed to perform that data motion after we add the new columns, and before we drop the old columns.

However, using the new columns in my query seems to cause problems, probably because of something like an entire migration being executed as a batch or something.

In this example, the new column being added is BName, and it's just a simple exercise in populating it with the Name column from B. Prior to the migration's execution, BName does exist on A.

UPDATE [dbo].[A] SET a.[BName] = b.[Name], 
FROM [dbo].[A] a
FULL OUTER JOIN [dbo].[B] b ON a.[BId] = b.[Id]

This yields:

System.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "a.BName" could not be bound.

I've tried breaking up the batch with GO commands inside the queries I pass to Sql(), but they're not supported in this toolset.

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'GO'.

What's the best way to get around this considering the current state of EF? I searched around and found some suggestions of performing the schema change and the data motion in separate migrations, but I find this to be decently unpalatable because of the logical atomicity of this change. Maybe I could struggle enough with EF to develop two separate migrations in parallel so that I could check them into source control at the same time, but I'm forseeing lots of unnecessary pain in order to get that done merely for the sake of organization.

EDIT: For what it's worth, the documentation on EFCF Migrations seems to indicate that this is supported. Yet mine is still broken. However, I am filled with hope that this is just a stupid mistake on my part and not a shortcoming of the framework.

4

1 回答 1

2

看起来这可能只是上述查询的语法问题。我稍微改变了一下,这似乎工作:

UPDATE [dbo].[A] SET [BName] = [B].[BName]
FROM [dbo].[A]
FULL OUTER JOIN [dbo].[B] ON [A].[BId] = [B].[Id]

我不知道为什么这会有所不同,尽管像这样直接使用表名感觉很奇怪,但我可以以将其搁置的名义做出让步。

于 2013-06-07T22:33:50.447 回答