使用与EntitySet的一对多关系,指定的强制转换无效

时间:2013-10-25 15:52:52

标签: c# sql linq

我正在开发一个针对.net 4的Windows应用程序,它可以从多个平台获取订单信息。我需要将数据存储在本地数据库中并决定使用LINQ to SQL,目前我的Order类有相当数量的代码来处理每个平台发送的数据,所以我一直在使用装饰器来添加属性到了类,而不是在Visual Studio中使用设计器。

它似乎主要工作,但是当查询数据库的订单时,它只会成功返回主订单数据并尝试枚举Items EntitySet,它会抛出“指定的强制转换无效”。例外。程序将正确地将订单插入Orders表,将订单行/项目插入OrdersLines表,它还将读取OrdersLines表并返回正确填充的OrderLine对象。

Database layout我对链接到Orders.orderID的OrdersLines有外键约束

类:

[Table(Name = "Orders")]
public class Order
{
    [Column(Name="orderID",IsPrimaryKey=true, IsDbGenerated=false)]
    public string OrderID;
    [Column(Name = "sourceID")]
    public int SourceID;
    [Column(Name = "statusID")]
    public int StatusID = 1;
    [Column(Name = "externalOrderID")]
    public string ExternalOrderID;
    [Column(Name = "deliveryName")]
    public string Recipient = "";
    [Column(Name = "deliveryCompany")]
    public string Company = "";
    [Column(Name = "deliveryAddress1")]
    public string Address1 = "";
    [Column(Name = "deliveryAddress2")]
    public string Address2 = "";
    [Column(Name = "deliveryAddress3")]
    public string Address3 = "";
    [Column(Name = "deliveryTown")]
    public string Town = "";
    [Column(Name = "deliveryCounty")]
    public string County = "";
    [Column(Name = "deliveryCountry")]
    public string Country = "";
    [Column(Name = "deliveryCountryISO")]
    public string CountryISO = "";
    public Country RMCountryData;
    [Column(Name = "deliveryPostcode")]
    public string Postcode = "";
    public Int64 TotalWeight = 0;
    public ShippingType ShippingType = ShippingType.Standard;
    public ShippingDestination ShippingDestination = ShippingDestination.International;
    [Column(Name = "email")]
    public string Email = "";

    private EntitySet<OrderLine> _Items = new EntitySet<OrderLine>();
    [Association(Name = "FK_OrdersLines_Orders", Storage = "_Items")]
    public EntitySet<OrderLine> Items
    {
        set
        {
            this._Items.Assign(value);
        }
        get
        {
            return this._Items;
        }
    }

    public Order() {  }

    public void Save()
    {
        OrderDataContext context = new OrderDataContext(String.Format(Settings.Default.ConnectionString, Settings.Default.DBUser, Settings.Default.DBPassword, Settings.Default.DBServer, Settings.Default.DBName));
        context.Log = Console.Out;
        var query = from o in context.Order where o.OrderID.Equals(this.OrderID) select o;
        var line = from l in context.OrderLine where l.OrderID.Equals(this.OrderID) select l;

        if (query.Count() == 0)
        {
            context.Order.InsertOnSubmit(this);
            context.SubmitChanges();
        }
        else
        {
            foreach (var customerOrder in query)
            {
                Console.WriteLine(customerOrder.OrderID);
                foreach (var orderItem in customerOrder.Items)
                {
                    Console.WriteLine(orderItem.Name);
                }
            }
        }
    }
}

[Table(Name = "OrdersLines")]
public class OrderLine
{
    [Column(Name = "localLineID", IsPrimaryKey = true, IsDbGenerated = true)]
    public int LocalLineID;
    [Column(Name = "orderID")]
    public string OrderID;
    [Column(Name = "lineID")]
    public Int64 LineID;
    public Int64 ProductID;
    [Column(Name = "sku")]
    public Int64 SKU;
    [Column(Name = "name")]
    public string Name;
    [Column(Name = "quantity")]
    public int Quantity;
    [Column(Name = "weight")]
    public Int64 Weight;

    public OrderLine() { }

    public OrderLine(Order Parent, Int64 SKU, Int64 LineID, string Name, int Quantity)
    {
        this.OrderID = Parent.OrderID;
        this.LineID = LineID;
        this.ProductID = 0;
        this.SKU = SKU;
        this.Name = Name;
        this.Quantity = Quantity;
        this.Weight = 0;
    }
}

public partial class OrderDataContext : DataContext
{
    public Table<Order> Order;
    public Table<OrderLine> OrderLine;

    public OrderDataContext(String connString) : base(connString) { }
}

在“foreach(customerOrder.Items中的var orderItem)”行中抛出异常

堆栈追踪:

at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v)
at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues)
at System.Data.Linq.CommonDataServices.DeferredSourceFactory`1.TryGetCachedObject(Object[] keyValues, T& cached)
at System.Data.Linq.CommonDataServices.DeferredSourceFactory`1.Execute(Object instance)
at System.Data.Linq.EntitySet`1.Load()
at System.Data.Linq.EntitySet`1.GetEnumerator()
at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()

1 个答案:

答案 0 :(得分:0)

从我在数据库布局中看到的内容(来自SQL Server Management Studio的屏幕截图?),“weight”和“lineID”列被定义为“Allow Nulls”。

但是,对于您发布的OrderLine类定义,LineIDWeight属性不是Nullable

[Table(Name = "OrdersLines")]
public class OrderLine
{
    // ...
    [Column(Name = "lineID")]
    public Int64 LineID;
    // ...
    [Column(Name = "weight")]
    public Int64 Weight;

Linq2SQL当然希望这些属性为Nullable,它可以解释为什么会得到Specified cast is not valid:分配可能会失败,因为列数据库类型与C#属性类型不匹配。

尝试使用此代码:

[Table(Name = "OrdersLines")]
public class OrderLine
{
    // ...
    [Column(Name = "lineID")]
    public Int64? LineID;
    // ...
    [Column(Name = "weight")]
    public Int64? Weight;

修改

我还注意到orderIdnvarchar(30)localLineIdint。在生成连接SQL语句时,Linq2SQL可能会出现问题,并且确实值得尝试将它们设置为相同的类型。

最后,这就是问题所在:

[Association(Name = "FK_OrdersLines_Orders", Storage = "_Items")]

应该是这样的:

[Association(Name = "FK_OrdersLines_Orders", Storage = "_Items", OtherKey = "OrderID")]