2011-08-12 38 views
0

我有我的LINQ到SQL类映射如下:LINQ到SQL复制引用关系

public class DbCategory 
{ 
    public EntitySet<DbProduct> Products { get; set; } 
    ... 
} 

public class DbProduct   
{ 
    public EntityRef<DbCategory> Category { get; set; } 
    ... 
} 

然后,我有我的通用模型作为

public class Category 
{ 
    public IList<Product> Products { get; set; } 
     ... 
} 

public class Product   
{ 
    public Category Category { get; set; } 
     ... 
} 

现在我想让我的产品

var products = from p in context.Products 
       select 
       new Product 
       { 
        Category = new Category 
        { 
         OtherProperty = p.Category.OtherProperty 
         ... 
         //Now how do I set 
         //the products for this category? 
        } 
       }; 

这应该很容易,如果我能先初始化产品实例,然后调用Category.Products.Add(this);

但是在一个linq语句中做这件事似乎很难。我错过了一些显而易见的东西,或者我的设计有缺陷?

回答

0

您可以创建一个辅助方法

private static Product CreateProduct(Category category) 
{ 
    Product p = new Product(); 
    p.OtherProperty = category.OtherProperty; 
    // set product or whatever of category 
    return p; 
} 

,然后通过你的helper方法创建。

var products = from p in context.Products 
       select 
       CreateProduct(p.Category);