2011-03-21 33 views
1

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

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

书籍

  • BOOKID
  • BookHref

评论

  • CommentId
  • 用户
  • 评论
  • BookId

我使用以下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> 

当我让脚手架做它的事,我得到代表多个字段的外键 Dynamic Data Output for Comments

回答

0

我相信,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列完全没有使用。

+0

我其实自己发现了这个,但是我没有更新这个帖子。 :) 非常感谢你的帮助。 – JustEngland 2011-03-21 13:18:41