[英]Linq to Sql entity associations (non integer primary keys)
我一直在使用Linq to Sql,但是在定義實體之間的關聯時遇到了一個問題。
我有2個表,一個是包含客戶交易的表,另一個是包含交易類型的查找表。 例如,交易可以是“ CASH”類型,並且查找表中的值將具有“ CASH”主鍵和“ Cash Payment”描述。
運行測試程序時,如果將事務和查找表中的主鍵更改為整數,則會收到“無法將類型為'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>);
}
}
忽略我,我已經回答了我自己的問題。
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,現在可以正常使用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.