开发者

LINQtoSQL - How do I get my query to recognize which table I want?

I'm using LINQtoSQL to create cascading deletes IE: if Category is deleted then all the Products in that category are also deleted.

I have a Products repository set up already (IProductsRepository) and now I'm working in my Category repository to add the business domain logic for the cascade.

Products repository has this method :

public void DeleteProducts(IList<Product> Products)
    {
        foreach (Product product in Products)
        {
            productsTable.DeleteOnSubmit(product);
        }
        productsTable.Context.SubmitChanges();
    }

Then I am creating a dele开发者_StackOverflow社区te category method in my Category repository:

    public void DeleteCategory(Category category)
    {
        IProductsRepository productsRepository;

        var CascadeDeleteProducts =
            from Products in productsRepository.Products
            where Products.CategoryID == category.CategoryID
            select Products;

        productsRepository.DeleteProducts(CascadeDeleteProducts.ToList());

        categoriesTable.DeleteOnSubmit(category);
        categoriesTable.Context.SubmitChanges();
    }

Visual Studio 2010 gives me an error in the above function for this line: from Products in productsRepository.Products. It says

Use of unassigned local variable 'productsrepository'

What could be causing this error? I'm creating the products repository through DI with this line: IProductsRepository productsRepository;. What am i doing wrong?

Edit

I neglected to mention that I am using Ninject to instatiate the product repository. So I beleieve that this line:IProductsRepository productsRepository; is effectually declaring and initializing the product repository.


You're creating an instance of your repository, but you never initialize it.

The line should look something like:

IProductRepository productsRepository = new ProductRepository();

Either that or you should allow the caller to inject (either method or constructor) the repository:

public void DeleteCategory(Category category, 
    IProductRepository productRepository)
{
}

UPDATE

If you're using nInject for your dependency injection, your method declaration should look like (this assumes you have nInject configured correctly to Inject the Dependency):

[Inject]
public void DeleteCategory(Category category,
    IProductRepository productRepository)
{
}


Exactly what Justin said...but just to clarify for you...

IProductsRepository productsRepository = new ProductsRepository();

But, you will likely run into issues here if each repository instantiates it's own DataContext object. In that case LINQ will object that you are working with the same related data in two separate DataContext objects (as each DataContext object you create keeps track of changed records).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜