我有两个EF模型 -
public class What
{
[Key]
public int primary_key_What { get; set; }
public int another_column_What { get; set; }
public virtual ICollection<Why> Whys { get; set; }
}
和
public class Why
{
[Key]
public int primary_key_Why { get; set; }
public int some_column_Why { get; set; }
public virtual What What { get; set; }
}
问题是,我必须使用 another_column_What 和 some_column_Why 在两者之间导航。正如您所看到的,它们都不是密钥或在数据库中声明为唯一的,它们的名称也不同。
我已经尝试了所有可以想象的方式并在搜索中找到了,但它们都没有用。我使用的模型映射的方式和位置,使用 another_column_What 和 some_column_Why 列在What和Why之间导航。
因此,只要EF生成查询,它就会将 another_column_What 与 some_column_Why 进行比较?
非常不幸的是,更改数据库体系结构(甚至列名称)不是一种选择。
有人可以帮我吗?
答案 0 :(得分:1)
这应该有效:
Db架构:
什么型号:
[Table("what")]
public class what
{
[Key]
[Column("primary_key_what")]
public int primary_key_what { get; set; }
[Column("another_column_what")]
public int another_column_what { get; set; }
public virtual ICollection<why> whys { get; set; }
}
为什么选择模型:
[Table("why")]
public class why
{
[Key]
[Column("primary_key_why")]
public int primary_key_why { get; set; }
[ForeignKey("what")]
[Column("some_column_why")]
public int some_column_why { get; set; }
public virtual what what { get; set; }
}
上下文:
public class Context : DbContext
{
public virtual DbSet<what> what { get; set; }
public virtual DbSet<why> why { get; set; }
public Context() : base("name=SqlConnection")
{
}
}
主:
static void Main(string[] args)
{
using (var context = new Context())
{
var results = from w in context.what
select w;
foreach (var what in results)
{
Console.WriteLine("what.primary_key_what = {0}", what.primary_key_what);
Console.WriteLine("what.another_column_what = {0}", what.another_column_what);
Console.WriteLine("what has {0} whys", what.whys.Count);
foreach (var why in what.whys)
{
Console.WriteLine("Why.primary_key_why = {0}", why.primary_key_why);
Console.WriteLine("Why.some_column_why = {0}", why.some_column_why);
}
}
}
}
什么数据:
为何数据:
输出: