Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all 1698 articles
Browse latest View live

How to select multiple columns that not using in group by?

$
0
0

I want to translate this SQL syntaxe to Linq:

select id, first_name, last_name, MAX(birthday)
from my_table
group by first_name

Thanks for you help


Duplicate Nested Using Blocks - A better way?

$
0
0

Hi All,

I know this isn't an MVC specific question and I'd appreciate a refrain from blurting out, "Use EF", but is there a design pattern or a better way to write a general ADO.net-like class to handle nested using blocks so that these aren't rewritten for every method that needs to query the database:

            using (OracleConnection cn = new OracleConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString))
            {
                cn.Open();
                using (OracleCommand cmd = new OracleCommand("", cn))
                {
                    using (OracleDataReader odr = cmd.ExecuteReader())
                    {
                        while(odr.Read())
                        {
                            ddlPositions.Items.Add(new ListItem(odr[1].ToString(), odr[0].ToString()));
                        }
                    }                    
                }
            }

Thanks,

Adam

Additional information: User without permissions.

$
0
0

 private StockTicker(IHubConnectionContext<dynamic> clients)
    {
        Clients = clients;

        //Posts
        var mapper = new ModelToTableMapper<Posts>();
        mapper.AddMapping(s => s.ID, "ID");

        _tableDependency = new SqlTableDependency<Posts>(
            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString,"tbl_Posts",
            mapper);

        _tableDependency.OnChanged += SqlTableDependency_Changed;
        _tableDependency.OnError += SqlTableDependency_OnError;
        _tableDependency.Start();
    }

Why I got this error? Additional information: User without permissions.

EF core entity update

$
0
0

Is this a valid update method in repo pattern within EF core to update attached entities.

public virtual void Update(TEntity obj)
{
           DbSet.Update(obj);
            var attachedObj = DbSet.Local.FirstOrDefault(e => e.Id.Equals(obj.Id));
            if (attachedObj != null)
            {
                var attachedEntry = DbContext.Entry(attachedObj);
                attachedEntry.CurrentValues.SetValues(obj);
            }
            else
                DbSet.Update(obj);
         }

Shorter Readable query in LINQ

$
0
0

Hello, I have created 2 queries that yield the same results, one is not very readable but is shorter:

var ppls = db.ProjectMembers
.Where(f => f.Project.ProjectStatusSet.Status == "Active" && f.IsContact == true)
                .Select(z => z.Person).GroupBy(p => p.Id)
                .Select(grp => grp.FirstOrDefault())
                .OrderBy(t => t.Name)
                .ToList();

and the other is readable but longer:

 var ppls =
                (from ppl in db.People
                 join pm in db.ProjectMembers
                     on ppl.Id equals pm.ProjectMember_Person
                 join p in db.Projects
                     on pm.ProjectMember_Project equals p.Id
                 join pss in db.ProjectStatusSets
                     on p.Project_ProjectStatus equals pss.Id
                 where pss.Status == "Active" && pm.IsContact == true
                 select ppl
                ).GroupBy(p => p.Id).Select(grp => grp.FirstOrDefault()).OrderBy(t => t.Name).ToList();

How can I make this readable and concise?

EF Core Migration with multiple provider always runs SQL Server scripts

$
0
0

I am using EF Core Code first and I have an issue when using multiple DB providers (SQL Server and MySql). Even when I choose to use MySql DB provider, SQL server migration files are used.

Check the sample project

Thanks in advance

LINQ to ADO.NET: Mapping a Data Model to an Object Model

$
0
0

I'm taking an ASP.NET course and I've been trying to rework an example in my textbook and while I've been able to get it to work with the included examples I can't figure out why it won't work in my own project. I believe the primary difference is the location of the database, the book example includes a local .mdf file whereas my project is using an offsite server. 

protected void Page_Load(object sender, EventArgs e) {

using (FakeMartEntities fakeMartProducts = new FakeMartEntities()) {

var fakeProducts = from fProducts in fakeMartProducts.tProducts
orderby fProducts.Description ascending
select fProducts;

ddlProducts.DataSource = fakeProducts;
ddlProducts.DataBind();
}

}

I receive the following error:

Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList().

I've done a few searches on this but none of the answers seem to take the same approach as my book and I'm perplexed as to why the book example does not throw this error. Also, the book recommends deleting the .tt files that are generated whenever adding an ADO.NET Entity Model.

submitChnages throw zombiecheck

$
0
0

hi everyone,

I have a code similar to this, which performs a commit of a single row to a database table (SQL 2008)

using(var db = new MyDbDataContext(_dbConnectionString)){
    Action action = new Action();
    db.Actions.InsertOnSubmit(dbAction);
    db.SubmitChanges();}

Normally everything is fine, but once in a while I get the following exception:

System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable.
at System.Data.SqlClient.SqlTransaction.ZombieCheck()
at System.Data.SqlClient.SqlTransaction.Rollback()
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)

There are a number of similar questions on SO but I after reading them I cannot work out the cause.

Could this be simply due to a SQL timeout (the exception occurs close to 30s after the call is made)?


how to check for NULL values?

$
0
0

I'm new to Entity Framework and I'm getting a null reference error that I'm not sure how to resolve.

In my DBContext class, in the onModelCreating method, I'm binding the database columns to the class that I am using.

My database column is called "cancelled_date" and my class property is "CancelledDate". My query that is returning the data has some records with null values in this column.

Here's my code snippet in the onModelCreating method:

...

entity.Property(e => e.CancelledDate)
.HasColumnName("cancelled_date")
.HasColumnType("datetime");

...

What attribute do I need to add to check for nulls? I tried putting a try/catch around this, but that did not work. 

Any suggestions? Thanks!

Automapper ignore prefix per map instead of globally

$
0
0

I want to remove a prefix from my source object, but I'd like to do it for each map an not globally, as it could cause issues where it's removing a column when it shouldn't. Is there an easy way to do this? This is what I'm working with right now

public partial class MappingProfile : Profile
{


    public MappingProfile()
    {
        //I would prefer this not to be a global and only remove the prefix on the specific map below
        RecognizePrefixes("Can");
        CreateMap<Candidate, CandidateVM>();
    }
}

Entity Framework Core Invalid Column after updating database table

$
0
0

I am using code first from the database using Asp.net core.

I have a table: UserRoles where I need to remove a CategoryId column and add in the OrganizationId reference.

Everything works, but when I go to delete (in order) my organizations, I try to delete from UserRoles first.  Well for some reason I am seeing the error below.

Any ideas?

System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'CategoriesCategoryId'.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__174_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<BufferlessMoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<MoveNext>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.<MoveNextCore>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Linq.AsyncEnumerable.AsyncIterator`1.<MoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

Here is my code to set my connection string. Now in my local SQL db, I do have multiple databases for initial categlog. Other tables DO have that column still because I haven't updated those databses. Could the appsetting json file be pulling another database for some reason?

        /// <summary>
        /// <para>
        /// Override this method to configure the database (and other options) to be used for this context.
        /// This method is called for each instance of the context that is created.
        /// 
        /// Note: All consuming applications must declare an appsettings.json file with connection strings - they must also add a dependency to
        /// Microsoft.Extensions.Configuration.Json
        /// 
        /// </para>
        /// <para>
        /// In situations where an instance of <see cref="T:Microsoft.EntityFrameworkCore.DbContextOptions" /> may or may not have been passed
        /// to the constructor, you can use <see cref="P:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.IsConfigured" /> to determine if
        /// the options have already been set, and skip some or all of the logic in
        /// <see cref="M:Microsoft.EntityFrameworkCore.DbContext.OnConfiguring(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)" />.
        /// </para>
        /// </summary>
        /// <param name="optionsBuilder">A builder used to create or modify options for this context. Databases (and other extensions)
        /// typically define extension methods on this object that allow you to configure the context.</param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if(!optionsBuilder.IsConfigured)
            {
                // Try to get the connection string from the hosted environment variables
                var connectionString = Environment.GetEnvironmentVariable("DefaultConnection");

                if (string.IsNullOrWhiteSpace(connectionString))
                {
                    // Fallback to appsettings.json in the host applications base directory
                    connectionString = ConnectionUtilities.GetConnectionString("DefaultConnection");
                }

                optionsBuilder.UseSqlServer(connectionString);
            }
        }
{"ConnectionStrings": {"DefaultConnection": "Data Source=mycomputername;Initial Catalog=MYTable;Integrated Security=True"
  }
}

EF How AddOrUpdate identify which is PK

$
0
0

when AddOrUpdate update data in table then how it understand which field is PK in table or unique row identifier because when we update then we write query like

update tablename set col='',col1='' where rowidentifier=value

public async <IActionResult> Edit(Customer customer)  
{  
    context.AddOrUpdate(customer)  
    context.SaveChangesAsync();  
    return RedirectToAction(nameof(Index));  
}  

How to join 2 IQuerables

$
0
0

I have 2 queries which have same table joins but different where conditions. I need to compare the result of these 2 queries. Instead of saying .ToList() on each query and getting the result into memory and comparing can I join these 2 IQuerables and then perform the comparison? My goal is to hit DB only once. Please help!!

INNER JOIN and GROUP BY

$
0
0

Hi, how do I convert this query into linq query?

select c.categoryname, sum(unitprice) from Products p
inner join Categories c on p.CategoryID = c.CategoryID
group by c.Categoryname

This is what i got:

var groupbyResultJoin = (from product in dc.Products
join category in dc.Categories
on product.CategoryID equals category.CategoryID
group product by product.CategoryID into productCategory
select new { Category = productCategory.Key, Total = productCategory.Sum(s => s.UnitPrice) });

But, i want to select category name instead of category id. if i change it at group, then i can't get the unit price from product table.

Just need quick clarification on Remove EF6

$
0
0

Hi

I have a complex model with 3 tiers

I want to Detach the 3rd tier from the second tier (remove the navigation link) but not delete them from the database

then I want remove the 2nd tier from the database completely

I am using EF6, how do I go about it

Is it something like

foreach(var one in OneModel)
{
foreach(var two in one.ModelTwo)
{
two.ThreeModel.Clear();//This detaches the third models
}
two.Remove()//This detaches the secondmodel
}
}

Any information would be appriciated.


Issue with a EF Model having a property that is also a Model

$
0
0

Hello,

I have an EF Model, lets call it Model 1, in C# that has 4 columns, CreatedBy, CreatedByDate,ModifiedBy,ModifiedByDate,

this model has a property that is a different model that has the same 4 properties, lets call that Model 2

When I reference the Model 2 in an MVC View, instead of showing the values for Model 2 for these 4 columns, it shows the values of those columns in Model 1.

Has anyone else encountered this same issue? Does anyone know of a solution?

Here is an example of what I am trying to do in C#

@model Model1

@if (Model1.Model2.Where(x => x.ProjectID == Model.ID).Count() > 0)
{
Model1.Model2 = Model1.Model2.Where(x => x.ProjectID == Model.ID).ToList();

foreach(var action in Model1.Model2)

{

<td>
@Html.Editor("CreatedBy", action.CreatedBy)
</td>
<td>
@Html.Editor("CreatedDate", action.CreatedDate)
</td>
<td>
@Html.Editor("ModifiedBy", action.ModifiedBy)
</td>
<td>
@Html.Editor("ModifiedDate", action.ModifiedDate)
</td>

}

Thank you,

George

Number of rows returned by a DataReader

$
0
0
Hi, Is there any way to know how many rows the data reader returns after executing a SQL statement? For now, I am doing the follwing:if datareader.hasrows then while datareader.read count += 1 end while end ifBut this method has its own problems. I think the "hasrows" property messes with the "read" method somehow, because if my datareader returns just 1 row, then it enters the if statement above, but doesn't go into the while statement!! Strange!!! please help if you can. Thanks a lot.

Authentication

$
0
0

I was just wondering if I could get some help on understanding what this block of code does, specifically : IdentityDbContext<ApplicationUser> . Thanks ! 

publicclassApplicationDbContext : IdentityDbContext<ApplicationUser>

    {

        public ApplicationDbContext()

            : base("DefaultConnection", throwIfV1Schema:false)

        {

        }

unable to import procedure

$
0
0

+i8tHi 

I have created a procedure in sql server and successfully added it in my asp.net application using db first approach. 

but after that i have created another procedure in sql server and i am trying again and again to import it in my application by clicking UPDATE MODEL FROM DATABASE

but the new procedure is not importing in application. However in dbcontext file it is adding new procedure reference. but in model new procedure is not adding.

please help me 

thanks

How to create linq query search from a list

$
0
0

I have a list of emails. I want to create a database query where I check if the query contains any of the emails and return them. My linq is not very good and i'm looking for help because this does not work:

IQueryable<Person> query = _context.Person;
List<string> emails = emailList;
foreach (var emailString in emails)
{
    query = query.Where(e => e.Epost == emailString);
}           

var personer = query.ToList();

any help? I'm just helpless when it comes to linq

Viewing all 1698 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>