gpt4 book ai didi

c# - 一个实体可以与多个实体相关联吗?

转载 作者:行者123 更新时间:2023-11-30 16:21:40 24 4
gpt4 key购买 nike

因此,假设我有以下实体及其上下文配置设置如下。为了简洁起见,我省略了很多属性:

public class Company {
public int Id { get; set; }
public Location Location { get; set; }
}

public class Customer {
public int Id { get; set; }
public Location Location { get; set; }
}

public class Location {
public int Id { get; set; }
}

public sealed class EntityDefaultContext : DbContext {
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Company>().HasKey(m => m.Id).ToTable("Company");
modelBuilder.Entity<Company>().Property(m => m.Id).HasColumnName("Id");
modelBuilder.Entity<Company>().HasRequired(m => m.Location).WithRequiredDependent().Map(m => m.MapKey("LocationId"));

modelBuilder.Entity<Customer>().HasKey(m => m.Id).ToTable("Customer");
modelBuilder.Entity<Customer>().Property(m => m.Id).HasColumnName("Id");
modelBuilder.Entity<Customer>().HasRequired(m => m.Location).WithRequiredDependent().Map(m => m.MapKey("LocationId"));

modelBuilder.Entity<Location>().HasKey(m => m.Id).ToTable("Location");
modelBuilder.Entity<Location>().Property(m => m.Id).HasColumnName("Id");
}
}

如您所见,Company 和 Customer 实体都持有对 Location 实体的引用。我相信这通常是意料之中的事情。

正如您也看到的那样,我为此设置了我的数据库上下文。但是 EF 生成的 SQL 非常低效:

SELECT 
[Extent1].[Id] AS [Id],
[Extent1].[LocationId] AS [LocationId],
[Extent3].[Id] AS [Id1]
FROM
[dbo].[Customer] AS [Extent1]
LEFT OUTER JOIN [dbo].[Company] AS [Extent2] ON [Extent1].[LocationId] = [Extent2].[LocationId]
LEFT OUTER JOIN [dbo].[Company] AS [Extent3] ON [Extent1].[LocationId] = [Extent3].[LocationId]
LEFT OUTER JOIN [dbo].[Company] AS [Extent4] ON [Extent1].[LocationId] = [Extent4].[LocationId]

这是在我做这样的事情时生成的:

var q = from c in defaultContext.Set<Customer>().Include(m => m.Location)
select c;

我这样做是出于与问题无关的原因。奇怪的是,如果我只将 Location 实体配置为仅由 Customer 实体关联,那么这里是 SQL:

SELECT 
[Extent1].[Id] AS [Id],
[Extent1].[LocationId] AS [LocationId]
FROM
[dbo].[Customer] AS [Extent1]
INNER JOIN [dbo].[Location] AS [Extent2] ON [Extent1].[LocationId] = [Extent2].[Id]

这是我所期望的。这让我思考。 EF不支持这种场景吗?怎么可能呢?

提前致谢。

最佳答案

您的原始映射使用一对一关系。这总是会导致一些特殊的行为。此外,它还有一些其他要求才能正常工作。您可能想要的是 CustomerLocation 以及 CompanyLocation 之间的一对多关系。将 WithRequiredDependent 更改为 WithMany,它应该可以工作。

关于c# - 一个实体可以与多个实体相关联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13004219/

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