0

我有以下代码将数据插入到 GiftCouponPayment 表和 Payment 表中。这段代码成功地创建了一个数据库和这两个表。但是,在一张表中没有插入数据 - GiftCouponPayment 表。需要进行哪些更改才能使其正常工作?

在此处输入图像描述

代码

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

}
}
4

1 回答 1

1

您不能在导航属性中使用界面 - EF 不支持它。您必须直接向班级申报您的付款:

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

如果您的付款可以有不同的PaymentComponents,您必须使用带有抽象基类而不是接口的映射继承。

于 2012-07-24T07:41:48.560 回答