使用 AddRange 的 C# 种子私有(private)成员

标签 c# .net-core .net-core-2.0

我有一个包含公共(public)成员和私有(private)成员的 Product 类。示例 UnitPrice 是私有(private)的。当我尝试播种数据时,我需要一种良好的语法方式来使用 Addrange 设置 UnitPrice。我将如何执行此操作?

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

如何查看数据?我无法设置单价,因为它无法访问。

        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    

最佳答案

你有一个接受这些参数的构造函数;使用它:

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 */) 
) }

关于使用 AddRange 的 C# 种子私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54703011/

相关文章:

java - 静态工厂是否适用于C#?

c# - 使用 C# 计算 Lat Long 是否在一个国家/地区内

c# - .net 核心中的 CPU 使用率(至少在 Windows 上)

asp.net-core - 带有 Cookie 和 Windows 身份验证的 ASP.NET Core

.net - 是否可以预热应用程序?

c# - 项目 'ClassLibrary1.csproj' 目标 'netcoreapp2.1' 。它无法被目标为 '.NETFramework,Version=v4.7.2' 的项目引用

c# - 在 .NET Framework 中将 .NET Standard 库与 Windows 兼容包结合使用

c# - 更新 wpf 中的 UI 元素

c# - 在 WinRT 中检查目录是否为空的简单方法(异步 API)

c# - 如何删除具有一个或多个空单元格或空单元格的行?