您好我在将数据集保存到通过外键关联的数据库时遇到问题。
这就是我所拥有的。
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
我在这里做错了什么?
答案 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();