Question

I am having trouble with foreign keys Dynamic Data and entity framework 4.0. It feels like there is a problem with the entity association but I am not sure. I have multiple fields representing the foreign key on the insert page. When I try and insert data I get an error A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'CommentId'

My data is a very basic one to many relationship, the foreign key in question is BookId in the Comment Table.

Books

  • BookId
  • BookHref

Comments

  • CommentId
  • User
  • Comment
  • BookId

I create the FOREIGN KEY with the following sql script.

ALTER TABLE [dbo].[Comments]  WITH CHECK ADD  CONSTRAINT [FK_Comments_Books] FOREIGN KEY([CommentId])
REFERENCES [dbo].[Books] ([BookId])

Entity Framework Generates the following XML

<EntityType Name="Books">
  <Key>
    <PropertyRef Name="BookId" />
  </Key>
  <Property Name="BookId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
  <Property Name="Title" Type="nvarchar" Nullable="false" MaxLength="255" />
  <Property Name="Description" Type="nvarchar" Nullable="false" MaxLength="2000" />
  <Property Name="Abstract" Type="nvarchar" />
  <Property Name="UserName" Type="nvarchar" Nullable="false" MaxLength="255" />
  <Property Name="Image" Type="varbinary(max)" />
  <Property Name="BookContent" Type="varbinary(max)" />
  <Property Name="rowguid" Type="uniqueidentifier" Nullable="false" />
  <Property Name="CreateDate" Type="datetime" />
  <Property Name="ModifiedDate" Type="datetime" />
</EntityType>
<EntityType Name="Comments">
  <Key>
    <PropertyRef Name="CommentId" />
  </Key>
  <Property Name="CommentId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
  <Property Name="UserName" Type="nvarchar" Nullable="false" MaxLength="255" />
  <Property Name="UserComment" Type="nvarchar" Nullable="false" />
  <Property Name="BookId" Type="int" Nullable="false" />
</EntityType>
<Association Name="FK_Comments_Books">
  <End Role="Books" Type="BookStoreModel.Store.Books" Multiplicity="1" />
  <End Role="Comments" Type="BookStoreModel.Store.Comments" Multiplicity="0..1" />
  <ReferentialConstraint>
    <Principal Role="Books">
      <PropertyRef Name="BookId" />
    </Principal>
    <Dependent Role="Comments">
      <PropertyRef Name="CommentId" />
    </Dependent>
  </ReferentialConstraint>
</Association>

When I let the scaffolding do its thing, I get multiple fields representing the foreign key Dynamic Data Output for Comments

Was it helpful?

Solution

I believe that FK should be:

ALTER TABLE [dbo].[Comments]  WITH CHECK 
ADD  CONSTRAINT [FK_Comments_Books] FOREIGN KEY([BookId])
REFERENCES [dbo].[Books] ([BookId])

You defined it on CommentId which creates 1:1 relation between Comment and Book and your BookId column in Comment is not used at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top