gpt4 book ai didi

c# - Entity Framework : Where the heck is it getting these columns from?

转载 作者:太空狗 更新时间:2023-10-29 20:28:38 25 4
gpt4 key购买 nike

我们正在尝试让 Entity Framework 在我们的商店中使用现有数据库(因此,更改数据库架构不是一种选择),而我们创建的用于测试事物的单元测试显示出一些非常奇怪的行为。

这是它为我们拥有的特定对象吐出的 SQL:

SELECT 
[Extent1].[CommentTypeId] AS [CommentTypeId],
[Extent1].[DataPartId] AS [DataPartId],
[Extent1].[CommentId] AS [CommentId],
[Extent1].[CreatedTime] AS [CreatedTime],
[Extent1].[Message] AS [Message],
[Extent1].[From] AS [From],
[Extent1].[Likes] AS [Likes],
[Extent1].[SourceTypeId] AS [SourceTypeId],
[Extent1].[StatusMessage_DataPartId] AS [StatusMessage_DataPartId],
[Extent1].[Album_DataPartId] AS [Album_DataPartId]
FROM [dbo].[Comments] AS [Extent1]

您可能会注意到,请求的最后两列与其他列不同。那是因为它们实际上并不存在,而且我们不知道 Entity 为什么要请求它们!我们的配置文件和 POCO 都没有提及它们。事实上,就我们的数据库而言,它们是完全不同的概念,根本没有直接关系。

它从哪里获取这些列,我该如何告诉它删除它们?

编辑:为了回答下面的一些问题,1) 我们正在使用 Entity Framework 4.2。我们正在使用流畅的映射。

2) POCO 本身看起来像这样,为了简洁起见,删除了相等的困惑:

public long DataPartId { get; set; }
public string CommentId { get; set; }
public DateTime? CreatedTime { get; set; }
public string Message { get; set; }
public string From { get; set; }
public int? Likes { get; set; }
public string SourceTypeId { get; set; }
public int CommentTypeId { get; set; }

public virtual DataPart DataPart { get; set; }
public virtual CommentType CommentType { get; set; }

3) 我们没有使用 edmx。我们有一个自定义的 DbContext。没有太多非常有趣的台词。这两个可能很有趣:

    Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;

除此之外,Context文件还有很多

modelBuilder.Configurations.Add(new WhateverConfiguration()) 

public IDbSet<WhateverPoco> PocoDatabaseTableAccessor { get; set; }

4) 我们从 db-first 开始,但那没有用,所以我们目前正在做代码优先。

5) 这是特定 POCO 配置的核心:

    HasRequired (x => x.DataPart)
.WithRequiredDependent (x => x.Comment);

HasRequired (x => x.CommentType)
.WithMany (x => x.Comments)
.HasForeignKey (x => x.CommentTypeId);

HasKey (x => x.DataPartId);
ToTable ("Comments", "dbo");

最佳答案

问题不在您显示的映射或类中。检查您的 AlbumStatusMessage 类。他们是实体吗?他们被映射了吗?他们有评论的集合导航属性吗?如果是,EF 预计 Comment 必须对这些表具有 FK。如果表格没有这样的列,则无法将这些导航属性映射到这些实体中。

顺便说一句。 Comments表中的id不应该是CommentId而不是DataPartId吗?

关于c# - Entity Framework : Where the heck is it getting these columns from?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8248639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com