外键映射

时间:2014-01-31 20:50:49

标签: c# linq linq-to-sql

我正在学习如何使用Linq-To-SQL

访问数据库

我刚创建了一个包含两个表的数据库文件

[Country]
(
   Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
   CountryName VARCHAR(100) NOT NULL
)

[Address]
(
   Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
   Street VARCHAR(100) NOT NULL,
   HouseNr VARCHAR(20) NOT NULL,
   ZipCode INT NOT NULL,
   City VARCHAR(100) NOT NULL,
   CountryId INT NOT NULL,
   CONSTRAINT [FK_Address_Country] FOREIGN KEY ([CountryId]) REFERENCES Country(Id)
)

现在我要创建一个名为Address的类。目前它看起来像:

[Table(Name = "Address")]    
public class Address
{
   [Column(IsPrimaryKey = true, IsDbGenerated = true)]
   public int Id { get; set; }

   [Column]
   public string Street { get; set; }

   [Column]
   public string HouseNr { get; set; }

   [Column]
   public int ZipCode { get; set; }

   [Column]
   public string City { get; set; }
}

我现在的问题是:如何将国家/地区映射为字符串属性?我读过关于协会的内容,但我真的不知道如何实现这个目标。

1 个答案:

答案 0 :(得分:1)

您需要使用Linq Mapping Attribute,如下所示

    private string _country;
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Country", CanBeNull=false)]
    public string Country
    {
        get
        {
            return this._country;
        }
        set
        {
            if ((this._country != value))
            {
                this._country = value;
            }
        }
    }