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

Sql DataReader

$
0
0

Hi Friends,

I have the below code where I am using a connection, sqlcommand, and sqldatareader to retrieve records from SQL Server. My question is I want to use the sqldatareader to loop through the returned results as you see I have a while loop below in the code section. My question is how would you recommend integrating this while loop into the code below it. Thanks !!!

                            while (rdr.Read())
                            {
                             var value= rdr["DataBaseName"];
                             }

 





public ActionResult ShowSSN(ShowSSN.Models.ShowSSNModel model)
        {
            string message;
            string status;

            if (ModelState.IsValid)
            {
                using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[model.connectionString].ConnectionString))
                using (var command = new SqlCommand("[dbo].[spGetSSN]", connection)
using (SqlDataReader rdr = sqlCommand.ExecuteReader())
{ CommandType = CommandType.StoredProcedure }) { try { connection.Open(); command.Parameters.Add(new SqlParameter("ssn", model.SSN));
//message = "SSN successfully deleted."; //status = "success"; } catch (SqlException e) { message = e.Message.ToString(); status = "danger"; } finally { connection.Close(); } } return View(model); } else { message = "Invalid fields entered."; status = "warning"; } TempData["message"] = message; TempData["status"] = status; return RedirectToAction("", "ShowSSN"); }


Adding New Field With Code First Approach on Production Environment

$
0
0

Hi guys,

I would like to add a new field to an existing table. I can do add migration and update database commands on thedevelopment environment. I wonder how can I update the production database?

Best Regards.

Linq query to database - Join

$
0
0

Hello,

I have question for you. 

I have 2 table, and one of them consist column for example "Operation" , and second table has columns with Name and Description. 

Now, I want to select all columns from first table, but in Operation field I want to pass value from Description field, because value from Operation equals value of Name in second table. I used Join method in Linq, and it works but "select" return only matching record.

I'm wondering how to write select with LINQ that return all matching data if value from "Operation" matching to value from "Name" but also retrun records if value from "Operation" doestn't matching to value from "Name" then return value from "Operation" field. 

In this moment in select statement I have for example 

.Select( table1.Id, table2.Description)

how to delete duplicated records in sqlserver

$
0
0

Greetings to all
Dear friends, I need to delete the records in the database table that have a specific duplicate field, but I don't know how to write the appropriate query for this operation. Please help us in this regard.

form example my table is like this : 

1    amir      6496   12

2    ali          1235    11

3    amir       4564    16

4     golo       1321    18

In this query it is necessary to show me the result of the table below

1    amir      6496   12

2    ali          1235    11

4     golo       1321    18

It doesn't matter which record is deleted, only the record with the duplicate field is deleted

problem with the entity

$
0
0

Hi,

I'm trying to learn blazor from online tutorials and now I encounter a problem:

When I write this entity I see a red line under both "options".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.EntityFrameworkCore;

namespace todo_try1.Data
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        public DbSet<ToDo> ToDoList { get; set; }

        //public DbSet<Category> Categories { get; set; }

        //public DbSet<Product> Products { get; set; }

        public override int SaveChanges()
        {
            return base.SaveChanges();
        }
    }
}

And when I build the project VS alarms me:

Severity Code Description Project File Line Suppression State
Error CS0311 The type 'todo_try1.Data.ApplicationDbContext' cannot be used as type parameter 'TContext' in the generic type or method 'DbContextOptions<TContext>'. There is no implicit reference conversion from 'todo_try1.Data.ApplicationDbContext' to 'Microsoft.EntityFrameworkCore.DbContext'. todo_try1 E:\Blazor_Try\todo_try1\todo_try1\Data\ApplicationDbContext.cs 12 Active

Please guide me to solve this problem.

TNX

Working with EF Core

$
0
0

I want to retrieve a subset of records from a table in an asp.net core app I'm building. Being old school I like to use stored procedures in Sql Server and in this instance the sp I've created uses this statement

Select * from tbl Where Field1=@param1 Or Field2=@param2

@param1 is a string, @param2 is an int

I have used a single parameter sp to return an object in my models successfully in the format:

return context.tbl.FromSqlRaw<entity>("spGetObject {0}", arg).ToList().FirstOrDefault();

but cannot find how to pass multiple parameters. These need to be any type including strings. So if someone can help with this I'd be very grateful. N.B. tbl=the name of the Sql Server table as defined in my AppDbContext class and entity is the name of one of the models in the application, i.e. public DbSet<modelname> tbl { get; set; }

I'd also like to return a list, (so omit the .FirstOrDefault() in the above code, and then traverse to an object in the list and use its values (fields) for processing. I could use a foreach loop but surely there is an easier way of doing this. If there is I'd appreciate help in this too

Best Regards

Andy

.Net Core migration keeps failing.

$
0
0

I cannot complete the following migration is their some reasoning behind the below error!

<div>PS C:\Users\Andrew\code\Bakery\wwwroot> dotnet ef migrations add CreateDatabase --output-dir Data/Migrations
Could not execute because the specified command or file was not found.
Possible reasons for this include:
* You misspelled a built-in dotnet command.
* You intended to execute a .NET Core program, but dotnet-ef does not exist.
* You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
</div>

Adding a new Context

$
0
0

I have a website Portal where there is one SPA application that I built in VS 2017 EF 6.0 Code First, Web API etc with a HTML/JavaScript front-end. 

I plan to add another independent application to the portal that will use the same VS project but points to a completely different database, albeit on the same server.

I plan to create a new ADO.NET Entity Data Model(Code First from Existing Database) and DbContext that points to the new application's database.
This is an existing database that is also used by an old Web Forms application I support, in a completely different website/server and VS solution.

I suddenly realized that any design changes I make on SQL Server to the existing database, inline with the Web Forms website requests, will cause trouble with Code First migrations, as it will detect changes not inline with the known CF Migrations schema. 
This could turn into a nightmare to support.

Any ideas to get around this.

Thanks for considering

 


Build failed error!

$
0
0

At what level of this project should i be trying to install this migration?  I want to install initial migrations to build my database form db context. Was having issues at first about update to ef migrations.. but it is now cleared. But i need to be installing from correct folder in order to make it work! I keep getting build failed error! Cowboy2

https://ibb.co/yddSrf2

I keep getting build failed error! In command Line terminal.

https://ibb.co/p43pLw4

These are the instructions from the project:

Now that the model configuration is complete and provision for seed data has been made, you can create the actual migration. Execute the following command from the terminal:

dotnet ef migrations addCreateDatabase--output-dirData/Migrations

This creates a migration called CreateDatabase. The files for the migration are generated in a newly created folder named Migrations in the Data folder (as specified by the value passed to the output-dir switch):   LearnRazorPages.com

But i have installed new migration dictionary as the previous instructions were not working!

And now their is the build failed  error.'

I believe that it is saying that i am missing using the correct folder to begin my tooling."

'NavigationExpandingExpressionVisitor query in ef core 3.1 error

$
0
0

Hello , i have a query that was working fine in ef core 2.2 but after changing to 3.1 and the changes i cant find the best way (or any way) to write this 

without getting this Error : 

InvalidOperationException: Processing of the LINQ expression 'DbSet<QuettaReq>
.Where(c => c.Category.CatName == __getCategoryWsupId_CatName_0 && c.OfferDate < DateTime.Now)
.Where(bb => !(__inList_1.Contains(bb.Id)))
.GroupJoin(
outer: DbSet<QuoteQuestion>
.OrderBy(a => a.QuoteId),
inner: quetta => quetta.Id,
outerKeySelector: qestion => qestion.QuoteId,
innerKeySelector: (quetta, joinQestionQuetta) => new ReqestWithQA{
ReqText = quetta.ReqText,
Qentity = quetta.Qentity,
CatId = quetta.CatId,
CatName = quetta.Category.CatName,
District = quetta.District,
ApplicationDate = quetta.ApplicationDate,
DeliveryDate = quetta.DeliveryDate,
OfferDate = quetta.OfferDate,
TecnicalDetails = quetta.TecnicalDetails,
Bedget = quetta.Bedget,
Id = quetta.Id,
QAViewModel = joinQestionQuetta
.Select(q => new QAViewModel{
Question = q.Question,
Answers = q.Answers,
Id = q.QuoteId,
QuoteQuestionId = q.QuoteQuestionId
}
)
.ToList()

the query in my controller : 

IQueryable<ReqestWithQA> fitReqests =
                    _context.Quetta
                    .Where(c => c.Category.CatName == getCategoryWsupId.CatName&& c.OfferDate > DateTime.Now)
                  .Where(bb => !inList.Contains(bb.Id)) 

                   .GroupJoin(_context.quoteQuestions.OrderBy(a => a.QuoteId),
                                quetta => quetta.Id,
                                    qestion => qestion.QuoteId, (quetta, joinQestionQuetta) => new ReqestWithQA
                                    {
                                        ReqText = quetta.ReqText,
                                        Qentity = quetta.Qentity,
                                        CatId = quetta.CatId,
                                        CatName = quetta.Category.CatName,
                                        District = quetta.District,
                                        ApplicationDate = quetta.ApplicationDate,
                                        DeliveryDate = quetta.DeliveryDate,
                                        OfferDate = quetta.OfferDate,
                                        TecnicalDetails = quetta.TecnicalDetails,
                                        Bedget = quetta.Bedget,
                                        Id = quetta.Id,
                                        QAViewModel =
                                            joinQestionQuetta
                                                .Select(q => new QAViewModel
                                                {
                                                    Question = q.Question,
                                                    Answers = q.Answers,
                                                    Id = q.QuoteId,
                                                    QuoteQuestionId = q.QuoteQuestionId
                                                }).ToList()
                                    }) ;

Thanks 

Model navigation property returns null value in my asp.net core project.

$
0
0

Hi

I have some entities like Patients with some relations to another entities. My problem is that, in Details view, the navigation properties (which points to other tables) does not display anything! apparently it returns null.

after a lot of search, some people says i should change some configation options in my dbContext (see this link), but i could not find Configuration property!

some people says Lazy loading is not supported by ef core, i should include it manually in my linq query (see this link), but also i could not find Include in my dbContext!!

Here is my Patients class :

public partial class Patients
{
        [Key]
        public Guid PatientRowID { get; set; }
        [Required]
        [StringLength(50)]
        public string PatientCaseID { get; set; }
        [StringLength(50)]
        public string PatientFname { get; set; }
        [StringLength(50)]
        public string PatientLname { get; set; }
	public int? SexID { get; set; }
	[ForeignKey(nameof(SexID))]
        [InverseProperty("Patients")]
        public virtual Sex Sex { get; set; }
}

And here is my another table (Sex) :

public partial class Sex
{
        public Sex()
        {
            Patients = new HashSet<Patients>();
            Persons = new HashSet<Persons>();
        }

        [Key]
        public int SexID { get; set; }
        [StringLength(50)]
        public string SexName { get; set; }

        [InverseProperty("Sex")]
        public virtual ICollection<Patients> Patients { get; set; }
        [InverseProperty("Sex")]
        public virtual ICollection<Persons> Persons { get; set; }
}

And here is my action method :

public IActionResult Details(string id)
        {
            if (string.IsNullOrEmpty(id))
                return BadRequest();

            Guid gid = Guid.Parse(id);
            var patient = _dbContext.Patients.Where(p => p.PatientRowID == gid).FirstOrDefault();
            if (patient == null)
                return NotFound();

            return View(patient);
        }

And here is my Details view code :

<div><dl class="row"><dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.PatientCaseID)</dt><dd class = "col-sm-10">
            @Html.DisplayFor(model => model.PatientCaseID)</dd><dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.PatientFname)</dt><dd class = "col-sm-10">
            @Html.DisplayFor(model => model.PatientFname)</dd><dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.PatientLname)</dt><dd class = "col-sm-10">
            @Html.DisplayFor(model => model.PatientLname)</dd><dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.SexID)</dt><dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Sex.SexName) // display nothing!</dd></dl></div>

Can anybody help me where is my problem & how to solve it?

Thanks in advance

Changing enum values to database

$
0
0

If i have a table with an enum column and then later i change the values in this enum, do i need to create a new migration and/or update database?

I have this enum for a property in my model:

public enum Response
{
   None,
   Yes,
   No
}

then i migrade to the database and begin using it as such in my app.

but then later i decide i need more options in that enum so i just add another value. Do i need to update the database, or is this irrelevant since it is an integer anyway?

I Can't create a migration identity

$
0
0

Hi,

I have a solution with some project (Api, Entities, Client, IdentityServer, ...)

I Create a migration in IdentityServer project for db of idetityserver so far so good. I try to create a migration also for asp identity core but doesn't work.

In this last case My context is in Entities RepositoryContext.cs

public class RepositoryContext : IdentityDbContext<User>
{
public RepositoryContext(DbContextOptions options) : base(options)
{
}

public DbSet<Blog> Blogs { get; set; }

#region Required
protected override void OnModelCreating(ModelBuilder modelBuilder)
{

    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<User>().Ignore(e => e.FullName);
    modelBuilder.Entity<UserFriend>().HasNoKey();

}
#endregion
}

When I execute this Add-Migration InitialIdentityDbMigration -c RepositoryContext -o Migrations/AspNetIdentity/AspNetIdentityDbin IdentityServer project

Obtain this

The DbContextOptions passed to the RepositoryContext constructor must be a DbContextOptions<RepositoryContext>. When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions<TContext> parameter rather than a non-generic DbContextOptions parameter.

BR

Header Column

$
0
0

HI ALL,

I have problem with Header Column from Excel file.It become trouble with dot "."

In excel Header column is "P 213.67(cps) and to load to webpages in controller as bellow;

controller



                            foreach (DataRow row in dt.Rows)
                            {
                                customers.Add(new Checking
                                {
                                    Price = row["P 213.67(cps)"].ToString(),
                                });
                            }

error message is;

System.ArgumentException
HResult=0x80070057
Message=Column 'P 213.' does not belong to table .
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>

somebody help me.

Fully code

1.controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using Test_Decimal.Models;

namespace Test_Decimal.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View(new List<Checking>());
        }
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase postedFile)
        {
            List<Checking> customers = new List<Checking>();
            string filePath = string.Empty;
            if (postedFile != null)
            {
                string path = Server.MapPath("~/Personal/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                filePath = path + Path.GetFileName(postedFile.FileName);
                string extension = Path.GetExtension(postedFile.FileName);
                postedFile.SaveAs(filePath);

                string conString = string.Empty;
                switch (extension)
                {
                    case ".xls": //Excel 97-03.
                        conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                        break;
                    case ".xlsx": //Excel 07 and above.
                        conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                        break;
                }

                conString = string.Format(conString, filePath);

                using (OleDbConnection connExcel = new OleDbConnection(conString))
                {
                    using (OleDbCommand cmdExcel = new OleDbCommand())
                    {
                        using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
                        {
                            DataTable dt = new DataTable();
                            cmdExcel.Connection = connExcel;

                            //Get the name of First Sheet.
                            connExcel.Open();
                            DataTable dtExcelSchema;
                            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                            string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                            connExcel.Close();

                            //Read Data from First Sheet.
                            connExcel.Open();
                            cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
                            odaExcel.SelectCommand = cmdExcel;
                            odaExcel.Fill(dt);
                            connExcel.Close();


                            foreach (DataRow row in dt.Rows)
                            {
                                customers.Add(new Checking
                                {
                                    Price = row["P 213.67(cps)"].ToString(),
                                });
                            }
                        }
                    }
                }
            }

            return View(customers);
        }
    }
}

2.Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Test_Decimal.Models
{
    public class Checking
    {
        public string Price { get; set; }
    }
}

3.Index

@using Test_Decimal.Models
@model IEnumerable<Checking>
@{
    Layout = null;
}<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Index</title></head><body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {<input type="file" name="postedFile" /><input type="submit" value="Import" />
    }
    @if (Model.Count() > 0)
    {<hr /><table cellpadding="0" cellspacing="0"><tr><th>P</th></tr>
            @foreach (Checking customer in Model)
            {<tr><td>@customer.Price</td></tr>
            }</table>
    }</body></html>

TransactionScope or EF Core Database.BeginTransactionAsync ()?

$
0
0

I know of two ways to start transactions in ASP.NET Core - the System.Transactions.TransactionScope class and the second method ( if you work with EF Core ) for the DbContext class of the Database property, the BeginTransaction () method. Please tell me how these methods differ, which one is better, more reliable? Thank!


what is the order of exeution in linq.

$
0
0

like in sqlserver we have following order of execution.

SELECT ORDER

FROM

  1. ON

  2. JOIN

  3. WHERE

  4. GROUP BY

  5. WITH CUBE or WITH ROLLUP

  6. HAVING

  7. SELECT

  8. DISTINCT

  9. ORDER BY

  10. TOP

can i get the same msdn page where they have written the above thing for both sntaxs of linq.

yours sinerley

VS 2019 - DBML File

$
0
0

I have downloaded a DBML file checked in by my colleague from TFS (VSTS Online). The entire project compiles. Once I make any minor change to the file, it prompts for changing the connection string. I click on YES.

The project refuses to compile after this change. I am adding 2 tables to the DBML file, but this addition and the change in the connection string is causing errors in the project. The connection string is pointed to the same database and has the same name.

Once I drop the two tables on the file, the changes made by my colleague disappear and the entire project refuses to compile.

Azure Connection

DataSet does not support System.Nullable.

$
0
0

Hello,

I am new to MVC and need help,I have got the above error when using crystal reports.

I have created a button on which the report should be download but I got this error on-click.

Please let me know the solution for this.

thanks.

Suggestions needed

$
0
0

Hi guys,

I have a database table that has two columns, gamecode, and clientcode. (https://ibb.co/3mzdrgZ)  At the beginning they were unique. I was querying as follows;

var productCodeReverse = _unitOfWork.ProductCodeRepository.GetByCode(p =>
                         p.gameCode == requestDto.productCode);
 public virtual TEntity GetByCode(Expression<Func<TEntity, bool>> where)
 {
    return dbSet.Where(where).FirstOrDefault();
 }

Now requirements slightly changed. I had to add the same gamecode (018000007177) which has unique clientcode (000000001111) in the table. Now I changed the query as follows;

 var productCodeReverse = _unitOfWork.ProductCodeRepository.GetSecondByCode(p =>
                          p.gameCode == requestDto.productCode, p =>
                          p.gameCode);
public virtual TEntity GetSecondByCode(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity,string>> orderBy)
{
   return dbSet.Where(where).OrderBy(orderBy).Skip(1).FirstOrDefault();
}

It is working but I wonder if there is some better way to accomplish what I did.

How can i check fo nulls in a Linq expression

$
0
0

I have the following :

if (user.Any(x => Guid.Parse(x.Id) == group.Id))

The issue is if x.id is null it fails . How can i do a check to only do the check if x.id is not null otherwise ignore ?

thanks

Viewing all 1698 articles
Browse latest View live


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