2

With Entity Framework, whenever I "update model from database" inside Visual Studio the model that's created isn't usable.

The issue is that EF doesn't handle tables without a primary key very well. It treats them as a view, which in turn prevents you from editing the table with EF. You can override this behavior by opening the model (edmx file) as an XML file and making a few changes to the EntitySet definition. It's annoying to do this over and over. Has anyone found a more permanent workaround besides adding a primary key or modifying the edmx file after every update?

By the way, I am using a unique key but it's spread across two columns. It'd be nice if EF could handle this, but as of EF 4.2 it doesn't.

Steve Wortham
  • 21,740
  • 5
  • 68
  • 90

2 Answers2

4

I don't understand - you're using a "unique key" (I assume you mean a unique index or a unique constraint) because the key has two columns? You can create a primary key with multiple columns. I'm not sure why EF would treat a two-column key differently than a single-column primary key, but here is a simple example of a multiple-column primary key:

CREATE TABLE dbo.foobar
(
    fooID INT,
    barID INT,
    PRIMARY KEY (fooID, barID)
);

Of course there is other syntax that allows you to create the constraint after the fact, and you should also name your constraint explicitly, but just wanted to show a simple example.

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
  • Ah ha. What I had before was a unique nonclustered key. I dropped that and added a two column primary key as you described. EF imports this just fine, and this solves the problem. By the way, I just found that you can add a multi-column primary key by selecting each column in SQL Management Studio, and click "Add Primary Key". Pretty neat, and funny I hadn't discovered that before. – Steve Wortham Jan 25 '12 at 00:44
3

By the way, I am using a unique key but it's spread across two columns. It'd be nice if EF could handle this, but as of EF 4.2 it doesn't.

Yes it does ;)

Community
  • 1
  • 1
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    Is this something that would work better with a Code First approach? The reason I ask is that the scenario I described above (Database First) is with a two-column unique key defined in SQL which isn't porting over to EF automatically. – Steve Wortham Jan 25 '12 at 00:25
  • I had the same issue. I had to go in and add a single primary key column, and make the two original columns a unique index. Then and only then would EF import the table correctly. – crichavin Mar 06 '13 at 04:32