我正在使用Entity Framework 5 code first
。我试图在2个表之间设置内部联接,我不知道如何去做。这两个表没有主键/外键关联,但它们有一个公共字段域。
tblServer表:
Server_ID
ServerName
Domain
...
...
tblCommandExecutionServer表:
ServerListID
ServerName
Domain
...
...
这就是我如何配置2个表来映射到某些实体类:
ServerConfiguration类:
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
}
答案 0 :(得分:6)
不支持将此类关系映射到导航属性。可以仅在主键的顶部映射关系(至少EF必须认为主体中的已定义列是PK)。为了支持Domain
中数据库Server
中的关系,必须是唯一的,但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
};