1
我正在使用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
}
看起來不錯。我需要填充其數據的Server類以及填充其數據的CommandExecutionServer類。你能否更新你的答案如何做到這一點? – 2013-03-07 08:40:20
你可以使用'new {s,c}'而不是場投影。 – 2013-03-07 08:49:50
這工作。我現在唯一需要它來設置返回的Server對象,將CommandExecutionServer設置爲c。我試過選擇新的'{s,s.CommandExecutionServer = c};'但它不想工作。 – 2013-03-07 10:38:44