Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 计算字段上的AspNetCore NullReferenceException异常_Asp.net_Razor_Asp.net Core - Fatal编程技术网

Asp.net 计算字段上的AspNetCore NullReferenceException异常

Asp.net 计算字段上的AspNetCore NullReferenceException异常,asp.net,razor,asp.net-core,Asp.net,Razor,Asp.net Core,我有一些带有计算字段的模型,可以正确地显示值,但当我试图编辑条目或创建新条目时,会出现NullReferenceException 型号: public class MMSPostage { public int ID { get; set; } [Display(Name = "Pieces")] public int PieceCount { get; set; } [DisplayFormat(DataFormatString = "{0:C3}")]

我有一些带有计算字段的模型,可以正确地显示值,但当我试图编辑条目或创建新条目时,会出现NullReferenceException

型号:

public class MMSPostage
{
    public int ID { get; set; }

    [Display(Name = "Pieces")]
    public int PieceCount { get; set; }

    [DisplayFormat(DataFormatString = "{0:C3}")]
    public decimal Rate { get; set; }

    [DisplayFormat(DataFormatString = "{0:C3}")]
    [Display(Name = "Total")]
    public decimal MMSSubTotal
    {
        get
        {
            return (Rate + JobType.Cost) * PieceCount;
        }
    }
    public JobType JobType { get; set; }
}
保存时引发NullReferenceException的编辑页面包括:

MMSPostage = await _context.MMSPostage
            .Include(m => m.JobType)
            .SingleOrDefaultAsync(m => m.ID == id);
上下文模型:

modelBuilder.Entity("SPM_Postage_Billing.Models.MMSPostage", b =>
                {
                    b.Property<int>("ID")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("PieceCount");

                    b.Property<decimal>("Rate");

                    b.HasKey("ID");

                    b.HasIndex("JobTypeID");

                    b.ToTable("MMSPostage");
                });
错误:

SPM_Postage_Billing.Models.mmspastage.get_MMSSubTotal()输入 mmspastage.cs + 退货(费率+作业类型成本)*计件;Microsoft.Extensions.Internal.PropertyHelper.CallNullSafePropertyGetter(Func getter,对象目标)


希望这是我忽略的简单的事情。我是AspNetCore的新手,因此非常感谢您的帮助

如果
JobType
mmspastage
之间的关系只是一对多,即1
mmspastage
有1
JobType
和1
JobType
有多个
mmspastage
s,则可以设置如下:

注意:

  • 我喜欢将持久性模型与域模型分开。因此,我的应用程序中有两组模型(除了视图模型)
  • 这是使用Microsoft.EntityFrameworkCore
    v2.0.3。对于v2.1.x,延迟加载功能已经恢复,实体可能看起来不同,因为您可能需要那里的
    virtual
    关键字
JobTypeEntity.cs 然后,您需要使用数据注释或Fluent API将实体属性配置为SQL表列。您可以像以前一样直接在
OnModelCreating()
上执行此操作,或者为每个实体创建配置类并在其中应用配置

JobTypeConfiguration.cs
免责声明:我手工编写了所有示例,因此它们未经测试,甚至可能未经编译。

我发现
JobType
mmspastage
之间存在关系。您需要向我们展示您是如何通过
EF-Core
配置关系的?异常看起来显然是
JobType
为空(您在这里执行了
JobType.Cost
)。您好,David,感谢您的回复。在SQL中,我有一个使用EF Core建立的外键关系。约束[FK_MMSPostage_JobType_JobTypeID]外键([JobTypeID])在删除集DEFAULTmodelBuilder.Entity(“SPM_Postage_Billing.Models.MMSPostage”,b=>{b.Property(“ID”).ValueGeneratedAnd();b.Property(“计件计数”)上引用[dbo].[JobType]([ID])b.财产(“费率”);b.HasKey(“ID”);b.HasIndex(“JobTypeID”);b.ToTable(“MMSPastage”);};你能把它贴在评论里吗?很难读。是的,当然,我错了
CONSTRAINT [FK_MMSPostage_JobType_JobTypeID] FOREIGN KEY ([JobTypeID]) REFERENCES [dbo].[JobType] ([ID]) ON DELETE SET DEFAULT

GO
CREATE NONCLUSTERED INDEX [IX_MMSPostage_JobTypeID]
    ON [dbo].[MMSPostage]([JobTypeID] ASC);
namespace DL.SO.Persistence.EFCore.Entities
{
    public class JobTypeEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Cost { get; set; }

        public List<MMSPostageEntity> MMSPostages { get; set; }
    }
}
namespace DL.SO.Persistence.EFCore.Entities
{
    public MMSPostageEntity
    {
        public int Id { get; set; }
        public int PieceCount { get; set; }
        public double Rate { get; set; }

        public int JobTypeId { get; set; }
        public JobTypeEntity JobType { get; set; }

        public double SubTotal
        {
            get
            {
               return (Rate + JobType.Cost) * PieceCount;
            }
        }
    }
}
namespace DL.SO.Persistence.EFCore.Configurations
{
    public class JobTypeConfiguration : IEntityTypeConfiguration<JobTypeEntity>
    {
        public void Configure<EntityTypeBuilder<JobTypeEntity> builder)
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.Name).IsRequired();
            builder.HasIndex(x => x.Name).IsUnique();
            builder.Property(x => x.Cost).IsRequired();

            builder.ToTable("JobType");
        }
    }
}
namespace DL.SO.Persistence.EFCore.Configurations
{
    public class MMSPostageConfiguration : IEntityTypeConfiguration<MMSPostageEntity>
    {
        public void Configure<EntityTypeBuilder<MMSPostageEntity> builder)
        {
            builder.HasKey(x => x.Id);

            // By default, public properties with getter and setter
            // will be included!
            // Since the computed property SubTotal only has getter,
            // it should not be included by default.
            // Just in case you worry about, you can do Ignore() too!
            builder.Ignore(x => x.SubTotal);

            // This is how you configure the 1-to-many relationship!
            builder.HasOne(x => x.JobType)
                .WithMany(jt => jt.MMSPostages)
                .HasForeignKey(x => x.JobTypeId);

            builder.ToTable("MMSPostage");
        }
    }
}
namespace DL.SO.Persistence.EFCore
{
    public class AppDbContext : DbContext
    {
        public class AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options) { }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            // You apply those configurations
            builder.ApplyConfiguration(new JobTypeConfiguration());
            builder.ApplyConfiguration(new MMSPostageConfiguration());
        }

        public DbSet<JobTypeEntity> JobTypes { get; set; }
        public DbSet<MMSPostageEntity> MMSPostages { get; set; }
    }
}
namespace DL.SO.Web.UI.Controllers
{
    public class PostageController : Controller
    {
        private readonly AppDbContext _dbContext;

        public PostageController(AppDbContext dbContext)
        {
           _dbContext = dbContext;
        }

        public IActionResult Edit(int id)
        {
            var postageEntity = _dbContext.MMSPostages
                    .AsNoTracking()
                    .Include(x => x.JobType)
                    .SingleOrDefault(x => x.Id == id);
            if (postageEntity == null)
            {
                return NotFound();
            }

            // Then you can construct your view model here!
            // Don't send your db entities directly to views man!
            var vm = new EditPostageViewModel
            {
                PostageId = postageEntity.Id,
                PieceCount = postageEntity.PieceCount,
                Rate = postageEntity.Rate,
                SubTotal = postageEntity.SubTotal,
                JobType = postageEntity.JobType.Name
            };

            return View(vm);
        }
    }
}