Search code examples
c#.net-core.net-core-2.0

C# Seed Private members with AddRange


I have a Product class with public and private members. Example UnitPrice is private. When I try to seed the data, I need a good syntax way to set UnitPrice with Addrange. How would I conduct this?

public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    private float UnitPrice { get; set; }

    public Product(int productid, string productname, string productdescription, float unitprice, string imagelocation)
    {
        ProductId = productid;
        ProductName = productname;
        ProductDescription = productdescription;
        UnitPrice = unitprice;
        ImageLocation = ImageLocation;
    }

How do I see the data? I cannot set Unit Price, since its inaccessible.

        if (!context.Product.Any())
        {
            context.Product.AddRange(
             new Product
             {
                 ProductName = "Samsung T3 Portable SSD - 500GB",
                 ProductDescription = "Superfast Read-Write Speeds of up to 450 MB/s; Shock Resistant & Secure Encryption",
                 UnitPrice = 5.50F,
                 ImageLocation = "Product1.jpg"
             },


Error Code:
    Severity    Code    Description Project File    Line    Suppression State
    Error   CS0122  'Product.UnitPrice' is inaccessible due to its protection level ElectronicsStore    

Solution

  • You have a constructor accepting these parameters; use it:

    if (!context.Product.Any()) { 
    {
       context.Product.AddRange(
          new Product(id, "Samsung T3 Portable SSD - 500GB",  "Superfast Read-Write Speeds of up to 450 MB/s; Shock Resistant & Secure Encryption", 5.50F, "Product1.jpg"), 
          new Product(/* parameters */) 
    ) }