【问题标题】:How do you insert foreign keys with Dynamic Data如何使用动态数据插入外键
【发布时间】:2011-07-19 08:35:25
【问题描述】:

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

我的数据是一个非常基本的一对多关系,有问题的外键是 Comment Table 中的 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>

当我让脚手架做它的事情时,我得到多个表示外键的字段

【问题讨论】:

    标签: asp.net entity-framework-4 asp.net-dynamic-data


    【解决方案1】:

    我认为 FK 应该是:

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

    您在 CommentId 上定义了它,这在 CommentBook 之间创建了 1:1 关系,而您在 Comment 中的 BookId 列根本没有使用。

    【讨论】:

    • 我实际上是自己发现的,但我没有更新帖子。 :) 非常感谢您的帮助。
    猜你喜欢
    • 2021-09-06
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    相关资源
    最近更新 更多