gpt4 book ai didi

entity-framework - 没有主外键关系的 Entity Framework 代码优先内部连接

转载 作者:行者123 更新时间:2023-12-01 00:40:40 24 4
gpt4 key购买 nike

我正在使用 Entity Framework 5 code first。我正在尝试在 2 个表之间设置内部连接,但我不确定该怎么做。 2张表没有主键/外键关联,但有一个共同的字段Domain。

tblServer 表:

Server_ID
ServerName
Domain
...
...

tblCommandExecutionServer 表:

ServerListID
ServerName
Domain
...
...

这就是我配置 2 个表以映射到某些实体类的方式:

服务器配置类:

class ServerConfiguration : EntityTypeConfiguration<Server>
{
internal ServerConfiguration()
{
this.ToTable("tblServer");
this.Property(x => x.Id).HasColumnName("Server_ID");
this.Property(x => x.Name).HasColumnName("ServerName");
}
}

CommandExecutionServerConfiguration 类:

class CommandExecutionServerConfiguration : EntityTypeConfiguration<CommandExecutionServer>
{
internal CommandExecutionServerConfiguration()
{
this.ToTable("tblCommandExecutionServer");
this.Property(x => x.Id).HasColumnName("ServerListID");
this.Property(x => x.Name).HasColumnName("ServerName");
}
}

服务器类:

public class Server : IEntity
{
public int Id { get; set; }

public string Name { get; set; }

public string Domain { get; set; }

public virtual CommandExecutionServer CommandExecutionServer { get; set; }
}

CommandExecutionServer 类:

public class CommandExecutionServer : IEntity
{
public int Id { get; set; }

public string Name { get; set; }

public bool IsActive { get; set; }

public string Domain { get; set; }

public virtual Server Server { get; set; }
}

这 2 个表未通过任何列链接。我必须创建以下内部联接但不确定如何创建:

SELECT
ces.ServerName,
ws.ServerName,
ws.Domain
FROM
tblServer ws
INNER JOIN tblCommandExecutionServer ces ON ws.Domain = ces.Domain
WHERE
ws.ServerName = 'my-server-name' AND ces.Active = 1;

我的数据库上下文类:

public DbSet<Server> Servers { get; set; }
public DbSet<CommandExecutionServer> CommandExecutionServers { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ServerConfiguration());
modelBuilder.Configurations.Add(new CommandExecutionServerConfiguration());
}

然后这就是我目前拥有的,我不知道它应该是什么样子?

public Server FindByServerName(string server, bool isActive, string domain)
{
return DatabaseContext.Servers
.SingleOrDefault(entity => entity.Name == server
&& entity.IsActive == isActive);
//&& entity.Domain == server
}

最佳答案

不支持将这种关系映射到导航属性。关系只能映射到主键之上(至少 EF 必须相信主体实体中定义的列是 PK)。为了支持您在数据库中的关系,Server 中的 Domain 必须是唯一的,但 EF 尚不支持唯一约束。

您只能使用手动 linq join 来执行类似的查询:

var query = from s in context.Server
join c in context.CommandExecutionServer on s.Domain equals c.Domain
where s.ServerName == server && c.Active == isActive
select new {
c.ServerName,
s.ServerName,
s.Domain
};

关于entity-framework - 没有主外键关系的 Entity Framework 代码优先内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15264893/

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