开发者

Linq-to-SQL copy reference relations

I have my Linq-to-SQL classes mapped as following:

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

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

Then I have my generic models as

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

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

Now I am trying to get my products

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? 
                   }
                };

This should be easy if I could instantiate the Product instance first, then invoke Category.Products.Add(this);

But doing this whole thing in one linq statement seems to be hard. Did I miss something obvious or my design is flawed?


You can create a helper method

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

and then create via your helper method.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜