0
我已在follwing 3个表:问题与EF代码优先许多一对多关系
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<ItemParameter> Params { get; set; }
}
public class ItemParameter
{
public int ID { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
要设置映射
CREATE TABLE [dbo].[Items](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL)
CREATE TABLE [dbo].[Params](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[DisplayName] [nvarchar](50) NOT NULL)
CREATE TABLE [dbo].[Params2Items](
[ParamID] [int] NOT NULL,
[ItemID] [int] NOT NULL,
[ID] [int] IDENTITY(1,1) NOT NULL)
和2相应的类我使用EntityTypeConfiguration类
public class ItemConfiguration : EntityTypeConfiguration<Item>
{
public ItemConfiguration()
{
HasKey(i => i.ID);
Property(i => i.Name).IsRequired();
HasMany(x => x.Params).WithMany(k => k.Items)
.Map(m => m.ToTable("Params2Items").MapLeftKey("ParamID").MapRightKey("ItemID"))
;
ToTable("Items");
}
}
当我尝试枚举Params集合时,我得到“已经有一个与此命令关联的打开的DataReader w必须先关闭它。“例外
static void Main(string[] args)
{
using (KMCatalog context = new KMCatalog())
{
foreach (var s in context.Items)
{
Console.WriteLine(s.Name);
foreach (var itemParameter in s.Params) //exception here
{
Console.WriteLine(itemParameter.DisplayName);
}
}
}
Console.ReadKey(true);
}
我用Ef中的Code First RC
哇,太好了,我想知道为什么这不标记为答案 – maztt 2012-05-06 18:35:11