Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6375021
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T01:33:38+00:00 2026-05-25T01:33:38+00:00

I have the following code: public void DeleteAccountsForMonth(int year, int month) { var result

  • 0

I have the following code:

public void DeleteAccountsForMonth(int year, int month)
{
    var result = from acm in this._database.AccountsOnMonth
                 where ((acm.Year == year) && (acm.Month == month))
                 select acm.Id;
    var query = (ObjectQuery<int>)result;

    string sql = string.Format(
        "DELETE FROM [AccountsOnMonth] WHERE [AccountsOnMonth].[Id] IN ({0})",
        query.ToTraceString()
    );

    var parameters = new List<System.Data.SqlClient.SqlParameter>();
    foreach (ObjectParameter parameter in query.Parameters)
    {
        parameters.Add(new System.Data.SqlClient.SqlParameter {
            ParameterName = parameter.Name,
            Value = parameter.Value
        });
    }

    this._database.Database.ExecuteSqlCommand(sql, parameters.ToArray());
}

Basically, what I’m trying to do is to delete a bulk of data from a context (get a query result, get SQL and execute it). But I’m having a problem when casting result to ObjectQuery. The exception that gives is

Unable to cast object of type
‘System.Data.Entity.Infrastructure.DbQuery1[System.Int32]' to type
'System.Data.Objects.ObjectQuery
1[System.Int32]’.

Can anybody give any hint to solve this? Thanks!

EDIT: Ladislav first solution helped me solve the problem, but it happenned a little problem with the SQL parameters of the generated SQL query, i.e. the SQL query generated by query.ToString() was this:

DELETE FROM [SncAccountOnMonths] WHERE [SncAccountOnMonths].[Id] IN (
    SELECT [Extent1].[Id] AS [Id]
    FROM [dbo].[SncAccountOnMonths] AS [Extent1]
    WHERE ([Extent1].[Year] = @p__linq__0) AND ([Extent1].[Month] = @p__linq__1))

The problem was that the variables @p__linq__0 and @p__linq__1 where not declared and so the query gave the error “Must declare the scalar variable @p_linq_0″ (I sure it would give the same error for variable @p__linq__1). To “declare” them I need to pass them as arguments of the ExecuteSqlCommand(). And so, the final solution for the initial answer is the code below:

public void DeleteAccountsForMonth(int year, int month)
{
    var result = (this._database.AccountsOnMonth
        .Where(acm => (acm.Year == year) && (acm.Month == month)))
        .Select(acm => acm.Id);
    var query = (DbQuery<int>)result;

    string sql = string.Format(
        "DELETE FROM [AccountsOnMonth] WHERE [AccountsOnMonth].[Id] IN ({0})",
        query.ToString()
    );

    this._database.Database.ExecuteSqlCommand(sql,
        new SqlParameter("p__linq__0", year),
        new SqlParameter("p__linq__1", month)
    );
}

By the way, I assume the variables generated always have the format @p__linq__, unless Microsoft’s Entity Framework Team changes it in any future EF update…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T01:33:39+00:00Added an answer on May 25, 2026 at 1:33 am

    That is because your _database is derived from DbContext and your AccountsOfMonth is DbSet<>. In such case you cannot use ObjectQuery directly because DbSet<> produces DbQuery<> which is not convertible to ObjectQuery<>.

    You must either use DbQuery<> directly:

    var result = from acm in this._database.AccountsOnMonth
                 where ((acm.Year == year) && (acm.Month == month))
                 select acm.Id;
    var query = (DbQuery<int>)result;
    
    string sql = string.Format(
        "DELETE FROM [AccountsOnMonth] WHERE [AccountsOnMonth].[Id] IN ({0})",
        query.ToString()
    );
    

    Or you must first convert your context to ObjectContext and create ObjectSet<>:

    var objectContext = ((IObjectContextAdapter)_database).ObjectContext;
    var set = objectContext.CreateObjectSet<AccountsOnMonth>();
    var resut = from acm in set
                where ((acm.Year == year) && (acm.Month == month))
                select acm.Id;
    

    The problem with first approach is that DbQuery doesn’t offer Parameters collection – just another example of simplification in DbContext API which only makes it harder to use.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code: public virtual void Initialise() { this.AddHeader(SystemContext, this.UserSettings.SystemContext); } public
I have the following code: public void DrawLetter(int Cell, string Letter, int X, int
SO I have the following code public void rand(int N){ double[]x=new double[N]; double[]y=new double[N];
I have the following code: public void myMethod(Object... args) { System.out.println(this is myMethod); }
I have the following code: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.screen_database); db=new DBAdapter(this);
Say have the following code: public void SaveOrUpdate(OrderContract orderContract) { foreach (var orderContract in
Let's say I have the following code: public void Inject(Form subform) { this.tabControl1.TabPages[1].Controls.Add(subform); this.Refresh();
i have the following code public static void main(String[] args) { int x=0; int
I have following code: public static void ProcessStep(Action action) { //do something here if
I have following code public class TEST { public static void main(String arg[]){ try

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.