2012-07-24 52 views
0

我有以下代碼將數據插入到GiftCouponPayment表和支付表中。此代碼成功創建了一個數據庫和這兩個表。但是,在一個表中沒有插入數據 - GiftCouponPayment表。需要改變什麼才能使其工作?數據未被插入:EF代碼優先

enter image description here

CODE

static void Main(string[] args) 
{ 

     string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30"; 

     using (var db = new NerdDinners(connectionstring)) 
     { 
      var giftCouponPayment = new GiftCouponPayment(); 
      giftCouponPayment.MyID=1; 
      giftCouponPayment.MyValue=250; 


      List<IPaymentComponent> comps = new List<IPaymentComponent>(); 
      comps.Add(giftCouponPayment); 
      var payment = new Payment { PaymentComponents = comps, PaymentID = 1, PayedTime=DateTime.Now }; 
      db.Payments.Add(payment); 

      int recordsAffected = db.SaveChanges(); 


     } 

} 

域類

namespace LijosEF 
{ 

public interface IPaymentComponent 
{ 
    int MyID { get; set; } 
    int MyValue { get; set; } 
    int GetEffectiveValue(); 
} 


public partial class GiftCouponPayment : IPaymentComponent 
{ 

    private int CouponValue; 
    public int MyID 
    { 
     get 
     { 
      return this.GiftCouponPaymentID; 
     } 
     set 
     { 
      this.GiftCouponPaymentID = value; 
     } 
    } 

    public int MyValue 
    { 
     get 
     { 
      return this.CouponValue; 
     } 
     set 
     { 
      this.CouponValue = value; 
     } 
    } 

    public int GetEffectiveValue() 
    { 
     if (this.GiftCouponPaymentID < 2000) 
     { 
      return 0; 
     } 
     return this.CouponValue; 
    } 

    public int GiftCouponPaymentID { get; set; } 

} 

public partial class Payment 
{ 
    public int PaymentID { get; set; } 
    public List<IPaymentComponent> 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; } 

} 
} 

回答

1

你不能在你的導航屬性使用的界面 - EF不支持它。您必須直接與類聲明付款:

public partial class Payment { 
    public int PaymentID { get; set; } 
    public List<GiftPaymentComponent> PaymentComponents { get; set; } 
    public DateTime PayedTime { get; set; } 
} 

如果您的付款可以有不同的PaymentComponents必須使用映射的繼承與抽象基類,而不是接口。