Asp.net 在EntityFramework4CodeFirstCTP5中,您实际上是如何执行关系的?

Asp.net 在EntityFramework4CodeFirstCTP5中,您实际上是如何执行关系的?,asp.net,entity-framework,asp.net-mvc-3,code-first,ef-code-first,Asp.net,Entity Framework,Asp.net Mvc 3,Code First,Ef Code First,我想举一个简短的例子,说明如何在EntityFramework4CodeFirstCTP5中实际执行关系 我想为这种关系举个例子: * one-to-many * many-to-many 非常感谢 一对一 public class One { public int Id {get;set;} public virtual Two RelationTwo {get;set;} } public class Two { public int Id {get;set;} public

我想举一个简短的例子,说明如何在EntityFramework4CodeFirstCTP5中实际执行关系

我想为这种关系举个例子:

* one-to-many
* many-to-many

非常感谢

一对一

public class One
{
  public int Id {get;set;}
  public virtual Two RelationTwo {get;set;}
}

public class Two
{
 public int Id {get;set;}
 public virtual One RelationOne {get;set;}
}
需要注意的是,它必须是虚拟的

一对多

public class One
{
  public int Id {get;set;}
  public virtual ICollection<Two> RelationTwo {get;set;}
}

public class Two
{
 public int Id {get;set;}
 public virtual One RelationOne {get;set;}
}
public class One
{
  public int Id {get;set;}
  public virtual ICollection<Two> RelationTwo {get;set;}
}

public class Two
{
 public int Id {get;set;}
 public virtual ICollection<One> RelationOne {get;set;}
}
公共一级
{
公共int Id{get;set;}
公共虚拟ICollection RelationTwo{get;set;}
}
公共二班
{
公共int Id{get;set;}
公共虚拟一个关系{get;set;}
}
多对多

public class One
{
  public int Id {get;set;}
  public virtual ICollection<Two> RelationTwo {get;set;}
}

public class Two
{
 public int Id {get;set;}
 public virtual One RelationOne {get;set;}
}
public class One
{
  public int Id {get;set;}
  public virtual ICollection<Two> RelationTwo {get;set;}
}

public class Two
{
 public int Id {get;set;}
 public virtual ICollection<One> RelationOne {get;set;}
}
公共一级
{
公共int Id{get;set;}
公共虚拟ICollection RelationTwo{get;set;}
}
公共二班
{
公共int Id{get;set;}
公共虚拟ICollection RelationOne{get;set;}
}
请注意,它需要是ICollection

以下链接可能会有所帮助,并且

希望这有帮助

编辑

更新为包含一对多

编辑#2

已更新,以包括进行评论要求的发票产品场景的可能性

注意:这是未经测试的,但应将您置于正确的方向

公共类发票
{
公共int Id{get;set;}
//…等。发票上的其他详细信息,链接到装运地址等。
公共虚拟ICollection项{get;set;}
}
公共类发票产品
{
公共int Id{get;set;}
公共整数数量{get;set;}
公共十进制价格{get;set;}//可能已计算
//…其他细节,如折扣可能
公共虚拟产品产品{get;set;}
公共虚拟发票订单{get;set;}//可能是但不是必需的
}
公共类产品
{
公共int Id{get;set;}
//…有关产品的其他详细信息
}

使用此功能,您可以遍历发票上的所有项目,然后foreach可以显示每个项目的发票详细信息以及产品本身的描述。

我认为它们不需要是虚拟的(但我强烈建议将其虚拟化)。如果它们未标记为虚拟,则关系仍将存在,但EF不会使用延迟加载,并且仅在相应实体已加载到会话中时才会加载关系的另一端。此外,对于一对多(one-to-many)来说,你的答案可以推断出它是如何实现的,它不需要双方的参考资料,尽管它可能有意义,但需要深入了解应用程序的需求。这只是你感兴趣的另一个链接,我发现它是一个非常有用的代码介绍:首先:感谢迄今为止的答案。还有一件事。如果在账单上下文中,您的发票有项目行。这将涉及一个关系表。你如何处理这个场景?更新为多加1-@Rushino你能把上面提到的场景再扩展一点吗?好的。我将把你放在一个账单的上下文中。您有一张发票(第一个实体)。发票包括产品(第二个实体),但发票上有包含您购买的产品数量的行。显然有一个关系表,其中包括IdLine、IdInvoice、IdProduct和QUOTE。如何首先使用EF4代码实现这个场景?