1

我在使用外键动态数据和实体框架 4.0 时遇到问题。感觉实体关联有问题,但我不确定。我在插入页面上有多个表示外键的字段。当我尝试插入数据时,出现错误ReferentialConstraint 中的依赖属性被映射到存储生成的列。列:“评论 ID”

我的数据是一个非常基本的一对多关系,有问题的外键是评论表中的 BookId。

图书

  • 书号
  • BookHref

评论

  • 评论 ID
  • 用户
  • 评论
  • 书号

我使用以下 sql 脚本创建了 FOREIGN KEY。

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

实体框架生成以下 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>

当我让脚手架做它的事情时,我得到多个表示外键的字段 用于评论的动态数据输出

4

1 回答 1

0

我认为 FK 应该是:

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

您定义了它,它在and和您的列CommentId之间创建 1:1 关系根本不使用。CommentBookBookIdComment

于 2011-03-21T07:05:11.687 回答