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

learning SQL

$
0
0

Hi, everybody. I have one question. What are the minimum requirements you need to know to learn the Entity framework?

I learn C#


Cannot create mdf file because it already exists

table has 2 records with the same ID and that by design... I can I get EF to process the records even if the records are Dups as Dups dont matter

$
0
0

Hi All. 

I have a table that captures records from using a service ... there is not validation or any table constraints as their are should need to be any.. (or should I just have sql reject them)

This is what I have and what I tested as well

var TestIfVlaid = XXX_DB.VUE_XXX.Where(r => r.XXX_REQ_ID == RID).Single();

var TestIfVlaid = XXX_DB.VUE_XXX.Where(r => r.XXX_REQ_ID == RID).SingleOrDefault();

var TestIfVlaid = XXX_DB.VUE_XXX.Where(r => r.XXX_REQ_ID == RID).First();

var TestIfVlaid = XXX_DB.VUE_XXX.Where(r => r.XXX_REQ_ID == RID).FirstOrDefault();

I read all the info in these items related to single and first but tried them all hoping something would work...

Any ideas of an easy way to do this?

Many thanks in advance!

ODBC connection string has me stumped...

$
0
0

Something changed between VB10 / Sql2008 and VB17/SQL12   I'm struggling.

Using OdbcConnectionStringBuilder(startstring), 

  • Giving it:  Driver={SQL Server};Server=`companyserverMSSQL.corp.this.com/instance`;Database=DBNAME;User ID=`DB_User`;Password=`Test1234`
  • Results in:  Driver={SQL Server};server=`companyserverMSSQL.corp.this.com/instance`;database=DBNAME;user id=`DB_User`;password=`Test1234`

15 second timeout.

Turns out error message details improve if you comment out your try..catch mechanism until this is fixed.

System.Data.Odbc.OdbcException
HResult=0x80131937
Message=ERROR [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.
ERROR [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
ERROR [01S00] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute

I am unable to find a way of giving the server address that makes this happy.

But, the query mechanism that uses an ODBC DSN in a CAD package works great!

consultations per year

$
0
0

I would like no entity to check the 3 customers who spent the most

thanks

Server Side Paging in WCF Data Service

$
0
0

I have created WCF service to retrieve data from SQL database. it returns huge amount of records; some times 200000 record.

so i need to create paging each page with size 1000 record. any help please ?

note : i retrieve data from SQL view not stored procedure 

Thank You 

Can't set a datatable cell to DBNull.Value

$
0
0

if (dtUBRecon.Rows[0]["prepStageID"].ToString() == "")
{
    dtUBRecon.Rows[0]["prepStageID"] = DBNull.Value;  << -- not working - looking at the datatable after, it is blank, when i try to do a db insert, it is missing the nulls.
}

any help is greatly appreciated.

Append the output of query into DataTable

$
0
0

Hi, I have a requirement to check if DataTable is null then copy the row to DataTable otherwise need to append the row to the DataTable. 

if(dtTable ==null){
        dtTable =(fromDataRow dr in dtDetails.Rowswhere dr["ID"].ToString()==Idselect dr).CopyToDataTable();}else{// Here Need to Add a new row in DataTable and append the output of 
         query intoDataTable ie dtTable.DataRow row = selectedTable.NewRow();

        dtTable  =(fromDataRow dr in dtDetails.Rowswhere dr["ID"].ToString()==Idselect dr)// Need help here}
Thanks.


WITH EXECUTE AS 'SqlUser1' EF Code First [Update-Database -Verbose]

$
0
0

I am trying to use the Entity Framework 6.1 Code First approach with generating my sql stored procedure. The issue is I need to supply the service account which to allow permissions to execute. Currently it is generating the procedure under my current AD account. Curious how I can implement this with the command CreateStoredProcedure.

I need to be able to execute a nuget package manager command called, "Update-Database -Verbose", that will generate the required SQL statement to create the database object. Below is what I need to do.

public partial class CreateStoredProcedureDelete : DbMigration
    {
        public override void Up()
        {
            CreateStoredProcedure("Delete", p => new { id= p.Int() },
                @"WITH EXECUTE AS 'SqlUser1'  
                    AS 
                 delete from XXX
        }
        public override void Down()
        {
            DropStoredProcedure("Delete");
        }
    }

Executing Update-Database -Verbose generates the following T-SQL 


CREATE PROCEDURE [Delete] @Id[int] AS BEGIN WITH EXECUTE AS 'SqlUser1' AS delete from XXX -- etc END

Then I receive an error from aforementioned code: Incorrect syntax near the keyword 'EXECUTE'.

Thanks.

Entity Framework Core Scaffold-DbContext

$
0
0

When I run the scaffold-dbconcontext command, for some reason it only created the primary key property of one of my models and omitted the other properties of this model. Do I need to set a parameter with the command to create all of the properties of the model? Thanks !

EF Core throw an exception on a duplicate PK or FK

$
0
0

Hello all!

Could you, please, provide me a simplest examples of this behavior when I'm trying to update one-to-one relationship in EF Core?

Thank you.

EF returning two identical records when 2 different records are in the table.

$
0
0

I have this method in my Music Entities class:

publicstaticList<Music> getMusic( decimal id, IDataProvider db )
{
  List<Music> data = db.MusicData.Where( m => m.id == id ).ToList<Music>();
 return data;
}

There are only 2 records in the database both with the same id field.

But this code returns two copes of the first of the two records.

How can I get all records for this id number?

 

 

How to use SqlBulkCopy with Entity Framework

$
0
0

Hi everyone, how do I use  Entity Framework with SqlBulkCopy,

Any help much appreciated, my problem is with the second method, not sure how to use Entity Framework with SqlBulkCopy...

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
        {
            DataTable csvData = new DataTable();

            try
            {
                using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                {
                    csvReader.SetDelimiters(new string[] { ";" });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    string[] colFields = csvReader.ReadFields();

                    foreach (string column in colFields)
                    {
                        DataColumn datecolumn = new DataColumn(column);
                        datecolumn.AllowDBNull = true;
                        csvData.Columns.Add(datecolumn);
                    }
                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();

                        //Making empty value as null
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }

                        csvData.Rows.Add(fieldData);
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            return csvData;
        }

        static void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData)
        {
            using (Entities dbcontext = new Entities())
            {
                SqlConnection sqlCon = (SqlConnection)dbcontext

                using (SqlBulkCopy s = new SqlBulkCopy(dbcontext))
                {
                    s.DestinationTableName = dbcontext.tablename;

                    foreach (var column in csvFileData.Columns)

                        s.ColumnMappings.Add(column.ToString(), column.ToString());

                    s.WriteToServer(csvFileData);
                }
            }

        }


 

add value to datatable column

$
0
0

I'm creating a datatable from a CSV file. However, I need to pre populate a column with today's date. When I try to do it, I get an error, [column 1 not found]. How can I create my table and pre populate a column with today's date in the data table column? I need to populate the TradeCreated Column with today's date.

code:

 DataTable dt = new DataTable();
            dt.Columns.Add("TradeId");
            dt.Columns.Add("TradeCreated");
            string readIt = File.ReadAllText(fileName);

            using (StreamReader sr = new StreamReader(fileName))
            {
              
                while ((line = sr.ReadLine()) != null)
                {
                     
                    if (!string.IsNullOrEmpty(line))
                    {
                        dt.Rows.Add();
                        
                        int count = 0;
                        foreach (string trades in line.Split(','))
                        {
                            dt.Rows[dt.Rows.Count - 1][count] = trades;
                            count++;
                        }
                    }

                }
            }

How Get Value Property in ASP.NET CORE MVC with C#

$
0
0

How Get Value Property in Class PROJECT.Project_Id from Class PROJECT_STATUS in ASP.NET CORE MVC with C# ???

Table/Class                                 Project                           R_SOURCE                             PROJECT_STATUS

----------------------------------------------------------------------------------------------------------------

Property/Field                           Project_id (pk)               Source_id (pk)                        status_id (pk)

                                                                                        Project_id (fk)

                                                                                         status_id (pk)


Export data from database to an existing excel sheet using ASP.NET

$
0
0

I have an Template Folder in which i have an Excel Sheet. I want to extract data from database and export it to Excel Sheet. Every time i click Export a copy of the Excel sheet in Template folder should be made and the data should be exported to the copy of the excel sheet and the sheet with data should get downloaded. Can this be done in C# ASP.Net ??

SQL to LINQ Lambda

$
0
0

Hello all,

I am new to LINQ. I have T-SQL but I like to convert it to LINQ lambda expression as follows:

SELECT DISTINCT p.Id, p.Date, p.LastName, p.FirstName, p.Gender, e.EventLocationId
FROM [dbo].[Vw_Personal] AS p
left join EventReservations r on (p.Id = r.Id)
left join Events e on (r.EventId = e.EventId)

I really appreciate your help. Thanks in advance.

An entity object cannot be referenced by multiple instances of IEntityChangeTracker with repository + unit of work

$
0
0

hello thank you for your help

again i have a probleme with an exception "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" when i try to add expense object to database

i heve used ADO.Net Entity Data Model with Entity Framework 5.0 for use model first

and i have used repository pattern with  unit of work here is the code like this tutorial

 (i have implemented a generic repository class that implement IGeneric Repository Interface)

here is my unit of work code

public class UnitOfWork : IDisposable
    {
        private InvoiceContext context = new SchoolContext();
        private GenericRepository<Invoice> _invoiceRepository;
        private GenericRepository<Expense> _expenseRepository;

        public GenericRepository<Invoice> InvoiceRepository
        {
            get
            {               
                return _invoiceRepository ?? new GenericRepository<Invoice>(context);;
            }
        }

        public GenericRepository<Expense> ExpenseRepository
        {
            get
            {

                get
            {               
                return _expenseRepository ?? new GenericRepository<Expense>(context);;
            }
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }

code business rule AddExpense

public void AddExpense(Expense expense, string out message)
{
    OnAdding(expense, out message);

    unitOfWork.ExpenseRepository.Add(expense);
    unitOfWork.Save();
}

private void OnAdding(Expense expense, string out message)
{
    if (expense.Invoice == null)
    {
        throw new BusinessRuleException("you can not insert an expense to invoice that's not existed");
    }

    if (expense.Invoice == State.Closed)
    {
        throw new BusinessRuleException("you can not insert an expense to invoice that's closed");
    }
//the rest of code
}

the model classes

public class Invoice
{
    public int Id {get; set;}
    //.....the rest of properies 
    public virtual List<Expense> Expenses{get; set;} 
}


public class Expense
{
    public int Id{get; set;}
    //.....the rest of properies 
    public virtual Invoice Invoice{get; set;} 
}

HOW TO CREATE MANY TO MANY RELATIONSHIP UISNG CODE FIRST APPROACH IN MVC

$
0
0

hi,

I have two classes like this deal and product want to create a  many to many relatioship followed this approach but getting error any help is appreciated

 public class Deal 
    {
        public int id { set; get; }

        public string Deal_Sku { get; set; }

        public string Deal_Name { get; set; }

        public decimal cost { get; set; }

        public  IList<DealProduct> DealProducts{ get;set;}
    }

 public class Product
    {
        public int ID { get; set; }
        public string Prod_SKU { get; set; }
        public string Prod_Name { get; set; }
        public double Price { get; set; }
        public  IList<DealProduct> DealProducts { get; set; }

    }
 public class DealProduct
    {
        public int DealId;
        public int ProductId;
        public Decimal Cost;
        public bool Free;
    }

I am trying to create codefirst like this but getting error
  public  DbSet<Product> Products { get; set; }
        public  DbSet<CartItem> CartItems { get; set; }

        public  DbSet<Deal> Deals { get; set; }

        public  DbSet<DealProduct> DealProducts { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
            //modelBuilder.Entity<DealProduct>()
            //     .HasKey(c => new { c.DealId, c.ProductId });
            //modelBuilder.Entity<Deal>()
            //    .HasMany(d => d.DealProducts)
            //    .WithRequired()
            //    .HasForeignKey(c => c.DealId);

            //modelBuilder.Entity<Product>()
            //    .HasMany(p => p.DealProducts)
            //    .WithRequired()
            //    .HasForeignKey(d => d.DealId);
        }

Create a filter with function in where clause

Viewing all 1698 articles
Browse latest View live


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