我正在用C#创建一个简单的应用程序。它的一个功能是添加发票。
为此,我在数据库中创建了两个表- Invoice和InvoiceLine,并使用实体框架为我映射它们。我需要为InvoiceLine类添加一些功能,但我知道您不应该编辑实体框架创建的代码。相反,我决定继承EF创建的类,并在这个类的基础上添加此功能。
我这样做了,但现在,当我试图将其保存到数据库时,我得到一个错误- 'System.InvalidOperationException:‘映射和元数据信息无法找到EntityType 'InvoiceRegister.Models.InvoiceLineModel’。
我的问题是--如何解决这个问题?另外,有没有更好的方法来实现我想要的?我想在MVVM中做我的项目,所以我想创建一个模型,而不是在我的ViewModel中做功能。
代码:
原始类(InvoiceLine):
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace InvoiceRegister.Models
{
using System;
using System.Collections.Generic;
public partial class InvoiceLine
{
public int DocEntry { get; set; }
public int LineId { get; set; }
public int LineNum { get; set; }
public string ItemName { get; set; }
public double Amount { get; set; }
public int TaxPrc { get; set; }
public decimal NetAmnt { get; set; }
public decimal TaxAmnt { get; set; }
public decimal TotalAmnt { get; set; }
public decimal Price { get; set; }
public virtual Invoice Invoice { get; set; }
}
}我的班级。我希望它继承自InvoiceLine:
namespace InvoiceRegister.Models
{
public class InvoiceLineModel : InvoiceLine, INotifyPropertyChanged
{
private double _amount;
public new double Amount
{
get { return _amount; }
set
{
_amount = value;
OnPropertyChanged("Amount");
OnPropertyChanged("NetAmnt");
OnPropertyChanged("TaxAmnt");
OnPropertyChanged("TotalAmnt");
}
}
private decimal _price;
public new decimal Price
{
get { return _price; }
set
{
_price = value;
OnPropertyChanged("Price");
OnPropertyChanged("NetAmnt");
OnPropertyChanged("TaxAmnt");
OnPropertyChanged("TotalAmnt");
}
}
private int _taxPrc;
public new int TaxPrc
{
get { return _taxPrc; }
set
{
_taxPrc = value;
OnPropertyChanged("TaxPrc");
OnPropertyChanged("TaxAmnt");
OnPropertyChanged("TotalAmnt");
}
}
public new decimal TaxAmnt
{
get
{
return NetAmnt* TaxPrc/100;
}
}
public new decimal NetAmnt
{
get
{
return (decimal)Amount * Price;
}
}
public new decimal TotalAmnt
{
get {return NetAmnt + TaxAmnt; }
}
public InvoiceLineModel()
{
this.LineNum = InvoiceViewModel.getNextLineNum();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}发布于 2019-03-31 21:23:57
您可以在代码优先的方法中执行此操作,但不能先在数据库中执行此操作,因此,基本上,您需要首先更新数据库。您使用的是数据库优先的方法,因此需要执行以下步骤:
1)直接在数据库中添加您的案例表("InvoiceLine")中的新字段
2)添加后,您可以通过右键单击并更新模型来更新EF生成的模型
3)更新时需要选中表复选框。(附图供参考)


4)一旦更新了EF模型,您就可以在EF生成的类中拥有可用的属性
帮助资源:https://entityframework.net/ef-database-first
全都做完了。
https://stackoverflow.com/questions/55441250
复制相似问题