我一直在玩Linq to Sql,但在定义实体之间的关联时,我遇到了一个问题。
我有2个表,1个是包含客户事务的表,另一个是包含事务类型的查找表。例如,事务可以是“CASH”类型,查询表中的值将具有“CASH”主键和“现金支付”描述。
当我运行我的测试程序时,如果我将事务中的主键和查找表更改为整数,则会得到“无法将类型'System.Int32'的对象强制转换为'System.String'”错误,该计划按预期工作。
我很遗憾地遗漏了一些基本的东西,但我不确定是什么。任何帮助表示赞赏。
这是我用来映射表格的代码:
[Table(Name = "customer")]
public class Customer
{
[Column(IsPrimaryKey = true, Name = "customer_id")]
public int CustomerID { get; set; }
private EntitySet<Transaction> _Transactions;
[Association(Storage = "_Transactions", OtherKey="CustomerID")]
public EntitySet<Transaction> Transactions
{
get { return this._Transactions; }
set { this._Transactions.Assign(value); }
}
public Customer()
{
this._Transactions = new EntitySet<Transaction>();
}
}
[Table(Name = "custtran")]
public class Transaction
{
[Column(Name = "compno", DbType="smallint")]
public int CompanyNumber { get; set; }
[Column(IsPrimaryKey = true, Name = "tran_no")]
public int TranNo { get; set; }
[Column(Name = "customer_id")]
public int CustomerID { get; set; }
[Column(Name = "tran_type", DbType="char(4)")]
public string TranType { get; set; }
private EntityRef<Customer> _Customer;
[Association(Storage = "_Customer", ThisKey = "CustomerID")]
public Customer Customer
{
get { return this._Customer.Entity; }
set { this._Customer.Entity = value; }
}
private EntitySet<TransactionType> _TransactionTypes;
[Association(Name="Custtran_TranType", Storage = "_TransactionTypes", IsForeignKey=true, OtherKey = "TranType")]
public EntitySet<TransactionType> TransactionTypes
{
get { return this._TransactionTypes; }
set { this._TransactionTypes.Assign(value); }
}
public Transaction()
{
this._Customer = default(EntityRef<Customer>);
this._TransactionTypes = new EntitySet<TransactionType>();
}
}
[Table(Name = "tran_type")]
public class TransactionType
{
[Column(Name = "compno", DbType = "smallint")]
public int CompanyNumber { get; set; }
[Column(IsPrimaryKey = true, Name = "tran_type", DbType="char(4)")]
public string TranType { get; set; }
[Column(Name = "description", DbType="Varchar(50)")]
public string Description { get; set; }
private EntityRef<Transaction> _Transaction;
[Association(Name="Custtran_TranType", Storage = "_Transaction", ThisKey = "TranType")]
public Transaction Transaction
{
get { return this._Transaction.Entity; }
set { this._Transaction.Entity = value; }
}
public TransactionType()
{
this._Transaction = default(EntityRef<Transaction>);
}
}
答案 0 :(得分:1)
忽略我,我已经回答了我自己的问题。
private EntitySet<TransactionType> _TransactionTypes;
[Association(Name="Custtran_TranType", Storage = "_TransactionTypes", IsForeignKey=true, ThisKey="TranType", OtherKey = "TranType")]
public EntitySet<TransactionType> TransactionTypes
{
get { return this._TransactionTypes; }
set { this._TransactionTypes.Assign(value); }
}
将ThisKey添加到协会,它现在可以正常工作。