实体框架6代码首先通过外键关系保存集合

时间:2014-07-28 11:27:08

标签: c# entity-framework entity-framework-5

您好我在将数据集保存到通过外键关联的数据库时遇到问题。

这就是我所拥有的。

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }

    public ICollection<Image> Images { get; set; }
}

public class Image
{
    public int ImageId { get; set; }
    public string ImageName { get; set; }
}

public class TestDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Image> Images { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

我试图保存下面的图像和产品。

 using (TestDbContext s = new TestDbContext())
            {        
                Product p = new Product() { ProductName = "test", Images = new List<Image>() {new Image{ ImageName="test"} } };
                s.Products.Add(p);
                s.SaveChanges();
            }

但是,我收到以下错误:

{"Invalid column name 'Product_ProductId'."}

修改

这是表结构

    CREATE TABLE [dbo].[Image](
        [ImageId] [int] IDENTITY(1,1) NOT NULL,
        [ImageName] [nvarchar](50) NULL,
     CONSTRAINT [PK_Image] PRIMARY KEY CLUSTERED 
    (
        [ImageId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] 


CREATE TABLE [dbo].[Product](
    [ProductId] [int] IDENTITY(1,1) NOT NULL,
    [ProductName] [nvarchar](50) NULL,
    [ImageId] [int] NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
(
    [ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Product]  WITH CHECK ADD FOREIGN KEY([ImageId])
REFERENCES [dbo].[Image] ([ImageId])
GO

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

如果要使用现有数据库,则需要从Product

中删除此属性
public ICollection<Image> Images { get; set; }

并在Image

上添加此属性
public ICollection<Product> Products { get; set; }

然后在OnModelCreating上添加以下配置。

modelBuilder.Entity<Image>().HasMany(i => i.Products).WithRequired().Map(m => m.MapKey("ImageId"));

最后以这种方式使用

var i = new Image() { ImageName = "test", Products = new List<Product> { new Product { ProductName = "test" } } };
s.Images.Add(i);
s.SaveChanges();