简体   繁体   中英

Entity framework 6 code first saving collection via foreign key relation

Hi i'm having issues saving a collection to database which is related via a foreign key.

This is what i have.

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>();
    }
}

I'm trying to save the images and products like below.

 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();
            }

However, i get the following Error:

{"Invalid column name 'Product_ProductId'."}

EDIT

Here is the table structure

    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

What am i doing wrong here?

If you to use the existing database, you need to remove this property from Product class

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

and add this property on Image class,

public ICollection<Product> Products { get; set; }

then add following config on OnModelCreating .

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

and finally use it this way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM