我正在使用实体框架代码第一种方法。我有以下代码将数据插入PaymentComponent和Payment表。插入PaymentComponent表的数据不正确。即使域对象中的相应属性不为null,它在两列(对于一条记录)中也具有NULL值。需要改变什么才能使其正常工作?
修改
当我在NerdDinners类中添加以下内容时,我得到以下结果 - 它有新的不需要的列
public DbSet<ClubCardPayment> ClubCardPayments { get; set; }
原始代码
static void Main(string[] args)
{
string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
using (var db = new NerdDinners(connectionstring))
{
GiftCouponPayment giftCouponPayment = new GiftCouponPayment();
giftCouponPayment.MyValue=250;
giftCouponPayment.MyType = "GiftCouponPayment";
ClubCardPayment clubCardPayment = new ClubCardPayment();
clubCardPayment.MyValue = 5000;
clubCardPayment.MyType = "ClubCardPayment";
List<PaymentComponent> comps = new List<PaymentComponent>();
comps.Add(giftCouponPayment);
comps.Add(clubCardPayment);
var payment = new Payment { PaymentComponents = comps, PayedTime=DateTime.Now };
db.Payments.Add(payment);
int recordsAffected = db.SaveChanges();
}
}
DOMAIN CODE
public abstract class PaymentComponent
{
public int PaymentComponentID { get; set; }
public abstract int MyValue { get; set; }
public abstract string MyType { get; set; }
public abstract int GetEffectiveValue();
}
public partial class GiftCouponPayment : PaymentComponent
{
private int couponValue;
private string myType;
public override int MyValue
{
get
{
return this.couponValue;
}
set
{
this.couponValue = value;
}
}
public override string MyType
{
get
{
return this.myType;
}
set
{
this.myType = value;
}
}
public override int GetEffectiveValue()
{
if (this.PaymentComponentID < 2000)
{
return 0;
}
return this.couponValue;
}
}
public partial class ClubCardPayment : PaymentComponent
{
private int cardValue;
private string myType;
public override int MyValue
{
get
{
return this.cardValue;
}
set
{
this.cardValue = value;
}
}
public override string MyType
{
get
{
return this.myType;
}
set
{
this.myType = value;
}
}
public override int GetEffectiveValue()
{
return this.cardValue;
}
}
public partial class Payment
{
public int PaymentID { get; set; }
public List<PaymentComponent> PaymentComponents { get; set; }
public DateTime PayedTime { get; set; }
}
//System.Data.Entity.DbContext is from EntityFramework.dll
public class NerdDinners : System.Data.Entity.DbContext
{
public NerdDinners(string connString): base(connString)
{
}
protected override void OnModelCreating(DbModelBuilder modelbuilder)
{
modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<GiftCouponPayment> GiftCouponPayments { get; set; }
public DbSet<Payment> Payments { get; set; }
}
参考:
答案 0 :(得分:3)
您尚未在datacontext中定义ClubCardPayment dbset。
插入此内容并且应该可以正常工作
public DbSet<ClubCardPayment> ClubCardPayments { get; set; }
答案 1 :(得分:3)
直接在基类中实施MyType
和MyValue
。 EF允许共享成员仅在基类中实现。在派生类中实现的成员在结果表中使用自己的列。
答案 2 :(得分:0)
您需要定义实际实现抽象类的2个类,这是EF了解不同类以及如何读取/更新/写入它们的实例的唯一方法。
(无需在EF中映射抽象类!)。
答案 3 :(得分:0)
这对您的问题没有任何帮助,只是来自我方的暗示:
为什么在派生类中实现MyValue和MyType explcitly?如果实现总是相同的话,你可以把它放到抽象类中......