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

Fetching logs efficiently

$
0
0

I have a simple log table where I store things like what, who and when:

public class Logg
{
   public int ID { get; set; }
   public string Name { get; set; }
   public string What { get; set; }
   public DateTime When { get; set; }
}

Ii'm wondering what is the best way of fetching this data from the db in the future when i have thousands and thousands of logs? 

I have a webage where users can see the last 10 entries of the log.  i don't need to change it in the future, so i'm thinking of  if a simple fetch query of the last 10 is performant enough? Most likely it is and I shouldn't use much time on this, but i want to know for academic reasons.

This is my query:,

 var logg = await _context.Loggs.OrderByDescending(d => d.When).Take(10).ToListAsync();

This will give me the 10 latest log entries. I'm worried that the process of ordering thousands of entries eventually would be expensive? An alternative could simply be to count the number of entries and take the last 10 id numbers since it starts at 1 (although deletions could mess this up. probably not the best idea). Another would be to not take 10 but do a linq and fetch on the latest month.


Do you think this tutorial is wrong or outdated

$
0
0

Hello,

I'm learning the Entity framework core and encountered in this tutorial:

You can see the page here:

https://entityframeworkcore.com/querying-data-basic-query

And in there comes:

Let's say we have a simple model which contains three entities.

public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public virtual List<Invoice> Invoices { get; set; }
}

Load All data

The following example loads all the data from Customers table.

using (var context = new MyContext())
{
    var customers = context.Customers.ToList();
}

This code isn't working. Is this wrong or outdated?

thanks,

how to include newline character in automapper?

$
0
0

hi, 

I'm using automapper to update fields in a database.  After the database is updated, the data can be viewed via web application.  I have one  field that contains data for three items. I would like to have each appear on a separate line so that it can be easily read.

I have tried adding \n\r  , \n, system.environment variable, <br>, <\br>, in between the items.  None of these have worked, everything just wraps and it's hard to read..  it looks like newline chars are being removed or ignored.  Do you have any suggestions to make this work?

Thank you!

MG

Get list of primary key column names in EF Core

$
0
0
ASP.NET MVC Core application using EF Core.

In linq to sql this code returns list of database table primary key columns names:

        /// <summary>
        /// Database primary key names
        /// </summary>
        public IList<string> DatabasePrimaryKey(Type dbContextPocoType)
        {
            List<string> pk = new List<string>();
            foreach (PropertyInfo p in dbContextPocoType.GetProperties())
            {
                var ca = p.GetCustomAttributes(typeof(ColumnAttribute), true);
                if (ca.Length == 0) continue;
                var atr = (ColumnAttribute)ca.Single();
                if (!atr.IsPrimaryKey) continue;
                pk.Add(atr.Name);
            }
            return pk;
        }

In EF Core I tried

            var entry = ctx.Entry(dbContextPocoType);
            var primaryKey = entry.Metadata.FindPrimaryKey();
            IList<string>  keys = primaryKey.Properties.Select(x => x.Name).ToList();
            return keys;

But this returns C# propery names.
How to get database table column names if EF Core?

How to create DbContext at runtime

$
0
0
ASP.NET 5 MVC Core application uses databases whose table columns are slightly different.

Npgsql EF Core provider is used.

How to create DbContext at runtime ? If dependency injection requires DbContext object first time, scaffold should create source code. This code should be compiled into assembly, this assembly shoud loaded into memory, DbContext constructor should called and resulting instance shoudl returned.

How to implement this ? Is there some NuGet package or framework for this ?

Prevent SQL Injection

$
0
0

I have this simple query executed in custom control.

SELECT StateID, StateName FROM State WHERE IsEnabled = 'TRUE' ORDER BY StateName

How can I prevent SQL Injection form this code?

One-to-many projection in a Web API NET5.0 controller - how to do it?

$
0
0

I set out to create a controller to retrieve Transaction properties for display purposes later on.

A single Txn has all the typical properties you would expect such as a TDate, IsPaid, the initials of the ServiceProvider and a Charge.

The charge is the total of the services provided, each Txn will have multiple Services each with their own rate (the 1-to-many).

My model looks like this

public class RecordDetail
    {
        public int TransactionId { get; set; }
        public string TDate { get; set; }
        public string BDate { get; set; }
        public string Initials { get; set; }
        public bool IsBilled { get; set; }
        public bool IsPaid { get; set; }
        public string SvcLevel { get; set; }

        public List<Service> Services { get; set; }

    }

and the controller:

[Route("DetailByClient/{pId}/{cId}")]
        [HttpGet]
        public async Task<ActionResult<List<RecordDetail>>> GetRecordDetailsByProvider(int pId, int cId) => await context.Transactions
            .Where(t => t.ProviderId == pId && t.ClientId == cId)
            .Select(t => new RecordDetail
            {
                TransactionId = t.TransactionId,
                TDate = t.Tdate != null ? t.Tdate.ToString() : "n/a",
                BDate = t.Bdate != null ? t.Bdate.ToString() : "n/a",
                Initials = t.Provider.User.Initials,
                IsPaid = t.IsPaid.HasValue ? (bool)t.IsPaid == true : (bool)t.IsPaid == false,
                SvcLevel = t.ProviderSvcTransactions.FirstOrDefault().ProviderService.ServiceLevel.SvcLevel,
                Services = (List<Service>)t.ProviderSvcTransactions
            })
            .ToListAsync();

This gives me the following error:

Unable to cast object of type 'System.Collections.Generic.HashSet`1[BtApiEf5.Model.ProviderSvcTransaction]' to type 'System.Collections.Generic.List`1[BtApiEf5.Model.Service]'.

I understand what it is complaining about, but I do not know how to fix it, or if I have made the right decision to do this in a single action.

Would appreciate your thoughts on how to proceed from here.

TIA

Scaffold in runtime

$
0
0

Tried to implement runtime scaffolding as described in

https://medium.com/@zaikinsr/roslyn-ef-core-runtime-dbcontext-constructing-285a9d67bc87

In project .config file


<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.2"><PrivateAssets>all</PrivateAssets><IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets></PackageReference> is changed to <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.2"/> After that yellow warning icons appear in Visual Studio Solution Explore Dependecies tree.
Build and package manager windows do not contain any warnings. How to find warning message related to this icon ? How to fix this ? Which is proper way to use scaffold in runtime ?


How to use EF Core pluralizer in runtime scaffold

$
0
0

Tried to use runtime scaffold in EF Core with NpgSql EF Provider

Created scaffolder as described in https://github.com/jdtcn/RuntimeEfCore :


using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Scaffolding; using Microsoft.EntityFrameworkCore.Scaffolding.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Npgsql.EntityFrameworkCore.PostgreSQL.Diagnostics.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Scaffolding.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal; using Humanizer; ... static IReverseEngineerScaffolder CreatePostgreScaffolder() { return new ServiceCollection() .AddEntityFrameworkNpgsql() .AddLogging() .AddEntityFrameworkDesignTimeServices() .AddSingleton<LoggingDefinitions, NpgsqlLoggingDefinitions>() .AddSingleton<IRelationalTypeMappingSource, NpgsqlTypeMappingSource>() .AddSingleton<IAnnotationCodeGenerator, AnnotationCodeGenerator>() .AddSingleton<IDatabaseModelFactory, NpgsqlDatabaseModelFactory>() .AddSingleton<IProviderConfigurationCodeGenerator, NpgsqlCodeGenerator>() .AddSingleton<IScaffoldingModelFactory, RelationalScaffoldingModelFactory>() // Type or namespace Bricelam not found // .AddSingleton<IPluralizer, Bricelam.EntityFrameworkCore.Design.Pluralizer>() .AddSingleton<IPluralizer, Humanizer.Pluralizer>() .BuildServiceProvider() .GetRequiredService(); } This causes two compile errors: > CS0234 The type or namespace name 'Pluralizer' does not exist in the> namespace 'Humanizer' (are you missing an assembly reference?)> > CS0411 The type arguments for method> 'ServiceProviderServiceExtensions.GetRequiredService<T>(IServiceProvider)'> cannot be inferred from the usage. Try specifying the type arguments> explicitly.

.NET 5 EF Core uses Humanizer for pluralization so it should exist.

How to scaffold in runtime from MVC Core application ?

How to use new version of DbContext assembly after old version is loaded

$
0
0

Entity Framework Core NpgSql MVC application uses  Scaffolded DbContext to access data.

DbContext is stored in separate assembly containing only this type.

If database structure is changed , new DbContext assembly is created in runtime using https://github.com/jdtcn/RuntimeEfCore as in-memory assemly.

This assembly can written to application home directory to replace existing DbContext.dll file.

After file is replacing application is still using old dbContext.dll file loaded at startup. How to force application to use new DbContext.dll file ?

How to force application to reload DbContext assembly so that new version is used?

ASP.NET 4.8 MVC re-loads application automatically if source dll file is replace . Is there similar feature it .NET 5 ?

Appilcation is running as Service in Debian Linux with Apache.

Making EF Core properties backward compatible with Linq-To-Sql

$
0
0

ASP. NET MVC 4.8 application uses DbLinq. 

Database has tables where column and table names are same:


CREATE TABLE Product ( Product CHAR(20) PRIMARY KEY ); Sql to Linq created entites with Contents property from them: public class Product ( public string Contents { get; set; } } Contents propery becomes part of published API used by third-party applications. EF Core scaffold creates property Product1 instead: public class Product ( public string Product1 { get; set; } }

This breaks API specification. How to make EF Core with API compatible ?

Is it possible to force it to generate Contents property as Sql to Linq ?

Or is it possible to add additional Contents property which actually gets and sets Product1 property values ?

Npgsql EF Core provider is used in ASP.NET Core MVC application.

insert for many to many relation in entity framework

$
0
0

hi team.

i am unable to insert the many to many relation useing

navigation property for 2 table..

if i have 2 table like student and hobbies.

studenthobbies contain primaray key of 2 table.

how can i insert via navigation property for studenthobbies table...or give some link 

[EF Core / DbContext] If I .Add() a row in a seperate thread, related tables/rows' state are set to EntityState.Added => Exception

$
0
0

Just to make it clear:

I use an injected instance of DbContext when it runs outside the thread, and a new DbContext() inside the thread.

Whether I run the code in a seperate thread or not, the ChangeTracker has Entries for the row I want to add, plus rows from all related tables.

The difference is that when I try to add a row in a seperate thread, all the related rows' EntityState are set to EntityState.Added:

db.VehicleWarehouse.Add(vehicleWarehouse);

entries = db.ChangeTracker.Entries();
cnt = entries.Count();

if (cnt > 1)
{
    foreach (var entry in entries)
    {
        var entity = entry.Entity;
        var state = entry.State;

        if (entity != vehicleWarehouse)
        {
            // all related tables ends up in a seperate entity, up to the very top (VehicleWarehouse->Vehicle->Company)

// if the code is in a seperate thread, State is always set to Added => Exception if (state == EntityState.Added) db.Entry(entity).State = EntityState.Unchanged; // prevent insert exception } } } db.SaveChanges();

I start the thread like this:

Task.Run(() => {
    FindVehicleWarehouse(vehicle, isLooking);
});

What could be causing this, and is there a way to prevent it from happening? 

Select one recent row for that record with group by two columns

$
0
0

I want to select the newest record ordering by RequestDate if that has the RoomStatus as Request having the same id RoomId and RequesterId.

I have written the following query but this doesn't help to produce the output in fact this is giving me the error:

var query = _dbContext.RoomReservation
                  .Include(x => x.Room)
                  .GroupBy(x => new { x.RoomId, x.RequesterId })
                  .Select(room => new
                  {
                      Status = room.First().Status,
                      RoomId = room.First().BookId,
                      Name = room.First().Room.Name
                  }).Where(x => x.Status == Domain.Roomtatus.Requested);

The error I am getting is:

.First()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

I mean to group by RoomIdRequesterId, order each key's item list by RequestDate descending, and pick the first.

Included Class

public class RoomReservation
{
    public int Id { get; set; }
    public RoomStatus Status { get; set; }
    public int RoomId { get; set; }
    public string RequesterId { get; set; }
    public Room Room { get; set; }
}

public class Room
{
    public int Id { get; set; }
    public string Name{ get; set; }
}

What is the correct way of Group By with multiple columns with an order by? What I am missing in my Linq query?

Nuget restores design elements when upgrading EF Core from 5.0.2 to 5.0.3

$
0
0

After upgrading EF Core packages from 5.0.2 to 5.0.3  runtime scaffold using

https://github.com/jdtcn/RuntimeEfCore  is broken.

The following namespaces do not exist anymore:

```
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Design.Internal;
using Microsoft.EntityFrameworkCore.Scaffolding.Internal;

```

Code  which creates  scaffolder 

```
        static IReverseEngineerScaffolder CreatePostgreScaffolder()
        {
#pragma warning disable EF1001 // Internal EF Core API usage.
            return new ServiceCollection()
                .AddEntityFrameworkNpgsql()
               // .AddLogging()
                .AddEntityFrameworkDesignTimeServices()
                .AddSingleton<LoggingDefinitions, NpgsqlLoggingDefinitions>()
#pragma warning restore EF1001 // Internal EF Core API usage.
                .AddSingleton<IRelationalTypeMappingSource, NpgsqlTypeMappingSource>()
                .AddSingleton<IDatabaseModelFactory, NpgsqlDatabaseModelFactory>()
                .AddSingleton<IProviderConfigurationCodeGenerator, NpgsqlCodeGenerator>()
                .AddSingleton<IScaffoldingModelFactory, RelationalScaffoldingModelFactory>()
                .AddSingleton<IPluralizer, HumanizerPluralizer>() >
                .BuildServiceProvider()
                .GetRequiredService<IReverseEngineerScaffolder>();
        }

```

throws compile error.  IReverseEngineerScaffolder  interface is not defined.

How to perform runtime scaffold using 5.0.3 packages ?

 Upgrading from 5.0.2 to 5.0.3 has changed line in project file

> <PackageReference Include="Microsoft.EntityFrameworkCore.Design"> Version="5.0.2"> to > <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.3">> <PrivateAssets>all</PrivateAssets>> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>> </PackageReference> How to fix this so that upgrades will not add additonal elements? After upgrade csproj should contain > <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.3">> </PackageReference>




Using EF as scoped service throws exception "A command is already in progress"

$
0
0

Using Npgsql EF data provider as scoped service throws exception.

To reproduce:

1. Configure ASP.NET 5 MVC Core application to use NpgSql EF provider as scoped service in StartUp.cs :>     public void ConfigureServices(IServiceCollection services)>         {>         services.AddHttpContextAccessor();>         services.AddScoped<MyDbContext>();>         ...

3. Use following method to get dynamic data as described in

https://github.com/dotnet/efcore/issues/1862#issuecomment-451671168

and in

https://stackoverflow.com/questions/55267883/efcore-fromsql-async

    partial class MyDbContext
    {
        async public Task<IEnumerable<T>> ExecQuery<T>(string sql, params object[] parameters) where T : class
        {
            using var db2 = new ContextForQueryType<T>(Database.GetDbConnection());
            var res = await db2.Set<T>().FromSqlRaw(sql, parameters).ToListAsync();
            return res;
        }
        class ContextForQueryType<T> : DbContext where T : class
        {
            readonly DbConnection connection;
            public ContextForQueryType(DbConnection connection)
            {
                this.connection = connection;
            }
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<T>().HasNoKey();
                base.OnModelCreating(modelBuilder);
            }
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseNpgsql(connection);
                base.OnConfiguring(optionsBuilder);
            }
        }
    }

Observed. Exception at line

    var res = await db2.Set<T>().FromSqlRaw(sql, parameters).ToListAsync();> Npgsql.NpgsqlOperationInProgressException (0x80004005): A command is> already in progress:    select ...> >    at> Npgsql.NpgsqlConnector.<StartUserAction>g__DoStartUserAction|233_0(<>c__DisplayClass233_0&> )    at Npgsql.NpgsqlConnector.StartUserAction(ConnectorState> newState, NpgsqlCommand command, CancellationToken cancellationToken,> Boolean attemptPgCancellation)    at> Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean> async, CancellationToken cancellationToken)    at> Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean> async, CancellationToken cancellationToken)    at> Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior> behavior, CancellationToken cancellationToken)    at> Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject> parameterObject, CancellationToken cancellationToken)> > ...


How to fix this so that scoped service can used ? Or is it reasonable to use Npgsql only as transient service in MVC Core application ?

                       

Error while trying to update database for sqlcachedependency.

$
0
0

I keep receiving the following messsage from the command prompt while trying to update database for sqlcachedependency.

What should I do? Where is the mistake? I'm following this post:

https://docs.microsoft.com/en-us/aspnet/web-forms/overview/data-access/caching-data/using-sql-cache-dependencies-cs

Copyright (C) Microsoft Corporation. All rights reserved.


Enabling the table for SQL cache dependency.

...............An error has happened.  Details of the exception:
A network-related or instance-specific error occurred while establishing a conne
ction to SQL Server. The server was not found or was not accessible. Verify that
 the instance name is correct and that SQL Server is configured to allow remote
connections. (provider: Named Pipes Provider, error: 40 - Could not open a conne
ction to SQL Server)

Unable to connect to the SQL database for cache dependency registration.



Not databound? Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

$
0
0

I can't seem to get a simple .NET application to recognize a databound control.  Basically I have a .NET application, this time in Visual Basic, with an Entity build from an existing database.  When I have tags like the following, I can't get it to do anything.

Since I'm between 3 different versions of VS, and I'm trying to use 2017 right now, I'd just need to know what I need to do to databound the textbox below to my database.  The entity framework is already there and the field ServiceRequestDate is just a date field that is in the database.  I'm looking for some code that makes the Submit button I'm using take the text box below and update the database.  I don't know where the databind needs to be.

            <div>
                <asp:TextBox ID="tbServiceRequestDate" runat="server" Text='<%# Bind("ServiceRequestDate") %>'></asp:TextBox>
            </div>

Code behind (as you can see I'm trying to get this to bind anywhere, or everywhere even though I only want it done when I load the page or when I click Submit):

    Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
        If Not Page.IsPostBack Then
            tbServiceRequestDate.DataBind()
        Else
            tbServiceRequestDate.DataBind()
        End If

    End Sub

    Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
        tbServiceRequestDate.DataBind()
    End Sub

The Entity Model name is EHSShippingEntities and I already have a database for it.  I get the following when attempting to run the code.

System.InvalidOperationException
  HResult=0x80131509
  Message=Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
  Source=App_Web_5tsnn3n3
  StackTrace:
   at ASP.default_aspx.__DataBindingtbServiceRequestDate(Object sender, EventArgs e) in C:\dev\EHSShipping\EHSShipping\Default.aspx:line 14
   at _Default.Page_Load(Object Sender, EventArgs e) in C:\dev\EHSShipping\EHSShipping\Default.aspx.vb:line 7

Once I get this one TextBox to work, the rest of this stuff which I haven't looked at in about 10 years will come back to me.  I have lots of text boxes on the form I'm actually trying to do and just need this one to work to get all the rest of the controls on the page to work eventually.

Any help getting the code I'm trying above to do the required update when I click Submit on the page would be greatly appreciated.  I just need this one to figure out the rest of them.  If you have other questions about my code, please ask and I will get back with you as soon as possible.

Thank you,

-D

Writing Parent and Child data at the same time.

$
0
0

Morning,

Hope someone can help with with this. I have two models:

    public class Parent
    {
        public int ParentID { get; set; }

        public string  Data { get; set; }

        public virtual ICollection<Child> Children { get; set; }
    }

    public class Child
    {
        public int ChildID { get; set; }
        public int ParentID { get; set; }

        public string Data { get; set; }

        public virtual Parent Parent { get; set; }
    }

What I would like to be able to do or know how to do is insert records into both in one hit. Something like the below:

        public async Task<IActionResult> CreateParent(Parent parent)
        {
            parent.Child.Add(new Child
            {
                Data = "SomeData"
            });

            _context.Add(parent);

            await _context.SaveChangesAsync();
        }

Obviously before the parent record is saved, I don't have the PK from the Parent table to put in the FK of the Child table and I believe that is why I am getting Object 'reference not set to an instance of an object.', but obviously I could be completely wrong.

I thought, wrong or right, it would potentially automagically add the FK as the insert would be as it would be a single Company object with a child contained.


Hope that makes sense and someone can help me out with this, cheers





Trim trailing spaces from retrieved strings in EF Core

$
0
0

ASP.NET MVC Core 5 application uses Npgsql Entity Framework Core Data Provider to get data from Postgres database using Entity Framework Core. Columns in database are defined as CHAR(n) type, like

    create table prpalk (
    sfirmanimi char(100);
    )

Column types cannot changed to varchar.

Using EF commands like string nimi = ctx.Prpalks.Single().Sfirmanimi; to get data, strings in application contain also trailing spaces. How to remove trailing spaces automatically ?

Is there some event in EF Core which can used to trim all string columns when returned to application ?

I havent found such setting in EF data provider, Npgsql or Postgres database.

Column types cannot changed to varchar type due to compatibility with existing legacy application.

Viewing all 1698 articles
Browse latest View live


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