我们使用EF 4.1和流畅的API从遗留数据库中获取数据(我们不允许更改).我们在创建两个表之间的关系时遇到问题,其中相关列不是主键和外键.
使用下面的类,我们如何配置之间的一对多关系Report,RunStat以便Report.RunStats返回字段相等的所有RunStat实体ReportCode?
public class Report
{
[Key]
public int ReportKey { get; set; }
public string Name { get; set; }
public int ReportCode { get; set; } // Can we associate on this field?
public virtual ICollection<RunStat> RunStats { get; set; }
}
public class RunStat
{
[Key]
public int RunStatKey { get; set; }
public int ReportCode { get; set; }
public DateTime RunDate { …Run Code Online (Sandbox Code Playgroud) c# entity-framework foreign-keys primary-key entity-framework-4.1
再次使用无法更改的旧数据库,并使用带有Fluent API的Entity Framework 4.1来仅读取数据.
public class Client
{
[Key]
public int ClientID { get; set; }
public string Name { get; set ;}
public virtual ICollection<Phone> Phones { get; set; }
}
public class Phone
{
[Key]
public int PhoneID { get; set; }
public string Number { get; set; }
public virtual Client Client { get; set; }
}
public class ClientPhone
{
[Key]
[Column(Order=0)]
public int ClientID { get; set; }
[Key]
[Column(Order=1)]
public int PhoneID { get; …Run Code Online (Sandbox Code Playgroud) 我有一个继承自抽象基础的上下文类AuditableDbContext : DbContext.在AuditableDbContext有两个参数,一个是审计师和一个用于审计到的上下文.
在继承的类中,我有一个默认的无参数构造函数,它使用null参数调用其他构造函数,然后在Database.SetInitializer<MyDbContext>(null)调用基础构造函数后调用的最终构造函数中.
问题是即使我这样做,我仍然在应用程序启动时在数据库服务器上获得db迁移调用.
public abstract class AuditableContext : DbContext
{
public AuditableContext(IAuditor auditor, DbContext auditContext)
{
// params can be null resulting in no auditing
// initialization stuff here...
}
}
public class MyDbContext : AuditableContext
{
// DbSets here...
public MyDbContext() : this(null, null) {}
public MyDbContext(IAuditor auditor) : this(auditor, null) {}
public MyDbContext(IAuditor auditor, DbContext auditContext)
: base(auditor, auditContext)
{
Database.SetInitializer<MyDbContext>(null);
}
}
Run Code Online (Sandbox Code Playgroud)
我在数据库中看到的查询是两个常见的迁移查询...
SELECT [GroupBy1].[A1] AS [C1]
FROM ( …Run Code Online (Sandbox Code Playgroud)