2011-05-28 119 views
2

我无法理解一件事。假设我已经有这些编码实体:关于LINQ to SQL的简单问题

[Table(Name = "Rates")] 
public class Rate 
{ 
    private EntityRef<Product> _Product; 

    [Column(IsPrimaryKey = true)] 
    public String RateID 
    { get; set; } 
    [Column] 
    public String ProductID 
    { get; set; } 
    [Column] 
    public Double VolumeInTons 
    { get; set; } 
    [Column] 
    public Decimal Volume 
    { get; set; } 
    [Column] 
    public Decimal Cost 
    { get; set; } 
    [Column] 
    public UInt32 Year 
    { get; set; } 

    [Association(Storage = "_Product", OtherKey = "ProductID")] 
    public Product Product 
    { 
     get { return this._Product.Entity; } 
     set { this._Product.Entity = value; } 
    } 
} 

而且

[Table(Name="Products")] 
public class Product 
{ 
    private EntitySet<Rate> _Rates; 

    [Column(IsPrimaryKey= true)] 
    public String ProductID 
    { get; set; } 
    [Column] 
    public String Name 
    { get; set; } 
    [Column] 
    public String Category 
    { get; set; } 

    [Association(Storage="_Rates", OtherKey="ProductID")] 
    public EntitySet<Rate> Rates 
    { 
     get { return this._Rates; } 
     set { this._Rates.Assign(value); } 
    } 
} 
  • 我应该有一个物理数据库具有相同表定义连接(在我的应用程序中使用的DataContext)?
  • 假设我已经创建了一个数据库。它应该包含相同的表定义还是LINQ to SQL创建它们?
+2

看看[这个](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.createdatabase.aspx)方法 – Reniuz 2011-05-28 06:31:53

回答

5

如果您已有数据库,则从Visual Studio连接到该数据库,然后将这些表拖放到DataContext的设计模式中。 Visual Studio会为你生成相应的类。

或者,您可能会遇到的答案是您已经拥有生成的类(例如:来自与数据库不同的系统),并且您希望根据类定义创建数据库。那么你应该在你的代码早期的某个地方调用一次DataContext.CreateDatabase(Reniuz也提到过),并创建数据库。请注意,在下次运行时,不需要再次创建数据库。

+0

好的。我已经看到了实现这一目标的例程。所以我应该从'DataContext'继承,并且只使用它的所有表格的组合? – lexeme 2011-05-28 07:01:33