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

Child tables lookup is not loading using Lazy loading

$
0
0

Hi,

I have a primary table and secondary table lookup where i will load secondary drop down values based on primary drop down selection. But secondary drop down is not loading when i am using lazy loading technique. 

 List<pr> rs = LookupSingleton.Instance.PReasonLookup
                                       .Where(x => x.StartDate != null))
                                       .ToList();

                foreach (Preasonclass pr in rs)
                {
                   List<SecondaryReason> secondaryReasons = pr.SecondaryReasons  -- getting error in this line
                                              .Where(x => x.StartDate != null))
                                              .OrderBy(x => x.Description).ToList();
                }

Can some on please advice ?

Thanks


Get all records help

$
0
0

Hi

I have a field in a table  which is simply for sorting and say I want to select all from "e" to "w", how do i do it?

Why did the validation controls stop working?

$
0
0

Hello,

Why did the validation controls stop working after the data source of GridView was changed to Entity Framework from SqlDataSource on a Web form which has double master pages? The combination isn't allowed?

The validation controls "RequiredFieldValidator", "RangeValidator", and "ValidationSummary" had worked just before I changed the data source to Entity Framework.

I'm coding it by C# in Visual Studio Professional 2017.

Please let me know if you need more information because I'm not familiar with questioning about like this.

Best regards,

Herokey

query syntax needed

$
0
0

Hi,

May I know what is the LINQ query syntax for this below?

Location obj = ne.Locations.First(x => x.LocationID == LocationID);

FK Column error - MVC Core 2 - SqlException: Invalid column name 'DepartmentID1'.

$
0
0

hi guys,
I have two simple classes with a Primary Key and FK relationship.

In the Sub_Department class, I get the error

> SqlException: Invalid column name 'DepartmentID1'.
System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__108_0(Task<SqlDataReader> result)


Here is my code

public class Departments_Category_Registration
{
[Key]
public int CategoryID { get; set; } // This is the PK
public Departments DepartmentID { get; set; } // this is a FK


and my Departments class with the PK

public class Departments
{
[Key]
public int DepartmentID { get; set; }
[Display(Name ="Departments")]
[Required]
public string Department_Name { get; set; }
[Display(Name ="Departments")]
[Required]
public string Description_Long { get; set; }
[Display(Name ="Short Description_Short")]
[Required]
public string Description_Short { get; set; }
public bool IsEnabled { get; set; }
}



however if I update my db to change the FK to department1 it works, funny thing is that I never used 1 in my code, I had changed it from ID to DepartmentID (if that helps)

Secondly, I thought I ask, if its wise to create a separate controller for each model or not ?

Ehi

How to select random id from database and display randomly on label

$
0
0

Currently, I'm working on the Lucky Draw system. So the process of the system is when user click on button draw it select a random id from database where table attendance="Present". I also want to make the output display like animated counter number. Can anyone help me on this.Thanks.

I stuck on the background code :

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;




public partial class _Default : System.Web.UI.Page
{
    string constr = ConfigurationManager.ConnectionStrings["lucky"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {


        
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(""))
            {

            }
        }
    }
}

Cannot insert data into database

$
0
0

I'm working on registration page that user will fill the form and sumbit into database. I got the problem with database. Can anyone shared with me idea/solution. Thanks.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Registration : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();

    protected void Page_Load(object sender, EventArgs e)
    {

        SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();

        con.ConnectionString = @"Data Source= (LocalDB)\MSSQLLocalDB; AttachDbFilename = 
           C:\Users\Nor  Asyraf  Mohd No\Documents\Visual Studio 2017\LuckyDraw\LuckyDraw\App_Data\lucky.mdf; 
            Integrated Security = True";


    }
    public void refresh()

    {

        txtId.Text = "";

        txtName.Text = "";

        DropDownList1.Text = "";

    }



    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        SqlCommand cmd = new SqlCommand("insert into EMPLOYEES(EMP_ID,EMP_NAME,EMP_DEPARTMENT) values('" + txtId.Text + "','" + txtName.Text + "','" + DropDownList1.Text + "')",con);
        cmd.CommandType = CommandType.Text;

        try

        {

            con.Open();

            cmd.ExecuteNonQuery();

            lblResult.Text = "Data inserted successfully";

            con.Close();

            refresh();

        }

        catch (Exception ex)

        {

            lblResult.Text = ex.Message;

        }


    }

    protected void btnClear_Click(object sender, EventArgs e)
    {

        refresh();

        lblResult.Text = "";

    }
}

help understanding EF , Transactions and Unit of Work

$
0
0

I am trying to understand transactions a little more, but I don't know how to test them, eg two people accessing the same records at the same time,so i have no realpractisein how they work.

Now i use a unit of work pattern in my solution, and it has no reference to a transaction Scope, so does it use transactions? and if so how does it work?

Now transactions as pessimitc concurrency, so are there any occations where i use both pessemtic and optomistic concurrency at the same time?

Lets say I want to assign a database record to a user, not only to update the UI to let other employees know someone if using that record but also prevent some concurrncy issues

do i:

//Start a transaction
//Get the records from the database
//Add a navigation propert to assign the employee
//save the changes

now if thats correct, at the point of me selecting the records, can anyone else select them? or change them?

if i am using a unit of work the transation points are removed does that still apply?

Now lets say i want to run other operations, if I am using a unit of work, am i right in assuming the transaction is looked until IDispose has ben run, or the IOC finisheds?

Any information would be appriciated.


inserting directory structure into SQL

$
0
0

Im trying to insert a directory and its subdirectories into SQL , its working great but i cant figure out how to insert the filenames of the files inside the subdirectory...

below is my complete code

private void button1_Click(object sender, EventArgs e)
        {
            DirectoryInfo root = new DirectoryInfo(@"D:\website\AIO_GO");
            using (DirectoryTreeLoader loader = new DirectoryTreeLoader())
            {
                loader.Load(root);
            }

            return;
          
        }

Class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Data.SqlTypes;

namespace CCMM
{
    class DirectoryTreeLoader : IDisposable
    {
        const string connectionString = "Server=.;Database=WAM;Trusted_Connection=True;";
        private SqlConnection Connection;
        private SqlCommand Command;

        private SqlParameter ParentDirectoryId;
        private SqlParameter DirectoryName;

        public DirectoryTreeLoader()
        {
            Connection = new SqlConnection(connectionString);
            Command = Connection.CreateCommand();
            ParentDirectoryId = new SqlParameter("@parent_id", SqlDbType.Int, 4);
            DirectoryName = new SqlParameter("@name", SqlDbType.VarChar, 256);

            ParentDirectoryId.IsNullable = true;

            DirectoryName.IsNullable = false;

            Command.Parameters.Add(ParentDirectoryId);
            Command.Parameters.Add(DirectoryName);
            Command.CommandType = CommandType.Text;
            Command.CommandText = @"
      insert dbo.directory ( parent_id , name ) values ( @parent_id , @name ) ;
      select id = scope_identity() ;".Trim();

            return;
        }

        public void Load(DirectoryInfo root)
        {
            if (Connection.State == ConnectionState.Closed)
            {
                Connection.Open();
                Command.Prepare();
            }

            Visit(null, root);

            return;
        }

        private void Visit(int? parentId, DirectoryInfo dir)
        {
            // insert the current directory
            ParentDirectoryId.SqlValue = parentId.HasValue ? new SqlInt32(parentId.Value) : SqlInt32.Null;
            DirectoryName.SqlValue = new SqlString(dir.Name);

            object o = Command.ExecuteScalar();
            int id = (int)(decimal)o;

            // visit each subdirectory in turn
            foreach (DirectoryInfo subdir in dir.EnumerateDirectories())
            {
                Visit(id, subdir);
            }

            return;
        }

        public void Dispose()
        {
            if (Command != null)
            {
                Command.Cancel();
                Command.Dispose();
                Command = null;
            }
            if (Connection != null)
            {
                Connection.Dispose();
                Connection = null;
            }
            return;
        }
    }
}

any help ?

Issue saving single quotes to database

$
0
0

I'm using .net 4.0 to insert textbox values into a sql database.  Whenever I try to insert single quotes into the database, the values are appearing as &#39.  How do I save single quotes to the database without having the value converted to #39?   

How to set index with one line of LINQ?

$
0
0

I need to get the inner text and then what index it is in the list.

Is there a way to do this inline without me having to foreach over the list and setting it?

     var teamNameOrder = doc.DocumentNode.SelectNodes(string.Format("//*[contains(@class,'{0}')]", "hide-mobile")).Select(s => new { InnerText = s.InnerText, Index = 0 }).ToList();

How to convert the below to Async Call

$
0
0

How would I convert this to an ASYNC call?

publicclassFoo{publicintId{ get;set;}publicint?ParentId{ get;set;}// other props}

You can get children of one item using:

List<Foo>GetChildren(List<Foo> foos,int id){return foos.Where(x => x.ParentId== id).Union(foos.Where(x => x.ParentId== id).SelectMany(y =>GetChildren(foos, y.Id))).ToList();}

For ex.

List<Foo> foos =newList<Foo>();

foos.Add(newFoo{Id=1});
foos.Add(newFoo{Id=2,ParentId=1});
foos.Add(newFoo{Id=3,ParentId=2});
foos.Add(newFoo{Id=4});GetChild(foos,1).Dump();// will give you 2 and 3 (ids)

Entity Not Updating in Database

$
0
0

I am following a pattern in an MVC controller to avoid overposting while updating a record.
I have left certain fields out of the View because I don't want the user to update these fields.
I then want to update the model using only the whitelisted fields.

In the controller I have an action that uses TryUpdateModel for this purpose.
It does not fail, and makes the call to update the context successfully.

The problem is, it just doesn't update the record in the database.

Here is the code.

[HttpPost, ActionName("Edit")]
        [ValidateAntiForgeryToken]
        public ActionResult EditPost(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            using (var dbContext = new CACS_GNS_DataContext())
            {
                var userToUpdate = dbContext.Users.Find(id);
                if (TryUpdateModel(userToUpdate, "",
                    new string[] { "User_First_Name,User_Last_Name,User_Email,Active,Role_Id,Position_Id" }))
                {
                    try
                    {
                        dbContext.SaveChanges();
                        return RedirectToAction("Index");
                    }
                    catch (DataException dex)
                    {
                        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                    }
                }
                return View(userToUpdate);
            }
        }

The pattern I am using works for another entity in the model withut a problem.

Stumped.

Entity Framework Exception error 1004, NullSentinelProperty mismatch on output?

$
0
0

Hi guys, 

Can someone take a look at the following example posted in StackOverflow almost an year ago.

I having the same problem.

StackOverflow question

Thanks!

One to many relationship without foreign key

$
0
0

I've problem with mapping ralations, which there is in existing database. 

Two tables: table1 and table2

table1 has fields: table1Id, table1Code, table1Field (table1Id is primary key)

table2 has fields: table2Id, table1Code, table2Field (table2Id is primary key)

And I've ralation one to many between table2 and table1 so I need in table2 object table2.table1 which will be filled by looking for table1 row in table1 by table1Code. Ofcourse I need ICollection<table2> inside table1.

There is reference in database "ALTER TABLE table2 WITH CHECK ADD CONSTRAINT [FK_table2_table1] FOREIGN KEY([table1Code]) REFERENCES table1 ([table1Code])"

I use https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator which generates mapping below

HasRequired(a => a.table1).WithMany(b => b.table2).HasForeignKey(c => c.table1Code);

and when try to use it I see that generated SQL compares table1Id with table1Code (I think that it's because of use table1Id as foreign key)

Is it possible to create such mapping between those two tables, which are connected by table1Code?


EF Code first and stored procedures

$
0
0

Hi,

I have started to develop a system where it is based on EF Code first. I have now a new requirement for complex reports that were developed using Stored Procedures. Since this is a code first project how do I import and use the stored procedures that were created by my client's database developer?

Thanks

Only exception handling in controller?

$
0
0

This is probably a question that has been done many times, but i find myself doing this some times:

I wonder if it is right to double exception handling where if I create a post in a database from the controller:

try
{
   _postRepository.Create(post);
}
catch (Exception)
{
    throw;
}

But then when I wrote the repository I also wrote an exception handling there. But whose responisbility is this(controller or repository), or should I actually write it both places?

Static Variables

$
0
0

As static variables are static for the whole web application, is it dangerous to declare sql specific variables as static :

public static class Database
{

public static SqlConnection Sql_Connection;
public static SqlCommand Sql_Command;
public static SqlDataReader Sql_DataReader;  etc....

}

Because FOR EXAMPLE: suppose 2 users might call SqlDataReader at the same time, the danger is that the result of one user might sent to the second one since the content (value) of the SqlDataReader is UNIQUE for the whole application.  is my assumption right?

Microsoft.EntityFrameworkCore.InMemory updates Attach entities

$
0
0

Hi,

I start to use Microsoft.EntityFrameworkCore.InMemory for testing purpose (with xunit and moq).

During my tests, I "discovered" that Microsoft.EntityFrameworkCore.InMemory update entities, even when they are marked as "Attach", while my controllers work as expected with any real database.

Is it the normal behavior for Microsoft.EntityFrameworkCore.InMemory?

Disconnected scenario during tests with Microsoft.EntityFrameworkCore.InMemory

$
0
0

Hi,

I want to test the EditPost method of controllers. To simulate database access, I use Microsoft.EntityFrameworkCore.InMemory.

But if I use Microsoft.EntityFrameworkCore.InMemory, I have to do something like this (for a given test):


[Fact]
public void Can_Edit_Customer_Email()
{
// Generate the needed data from Microsoft.EntityFrameworkCore.InMemory
DataGenerator();

// Arrange var customer = _context.Customers.Find(1); // Act customer.EmailContact = "john.doe@contoso.com"; HomeController target = new HomeController(_context); target.EditPost(1, customer); // Assert Assert.Equal("john.doe@contoso.com", _context.Customers.Find(1).EmailContact);
}

Otherwise, if I feed the target.EditPost method like this:

    // Act 
HomeController target = new HomeController(_context);
target.EditPost(1, new Customer {Id = 1, FirstName = "John", LastName = "Doe", Email = "john.doe@contoso.com"});

I get this "expected" exception:

System.InvalidOperationException : The instance of entity type 'Customer' cannot be tracked because another instance with the key value 'Id:1' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. 

With a real database, my controllers work as expected (as detached). I mean, the entities start to be tracked when I retrieve them in the EditPost() method, and stopped to be tracked when _context.SaveChanges() is called.

But in the Microsoft.EntityFrameworkCore.InMemory context, entities are tracked as soon as they are added (here with my DataGenerator() method), and nothing seems to be reset, when _context.SaveChanges() is called. So I get the aboveSystem.InvalidOperationException;

While the "Find() method etc…" way works fine, it does not reproduce the "actual context" of data submission (with all that implies, like test accuracy, etc).

So my question is:

  • How can I reproduce disconnected scenario during my tests with Microsoft.EntityFrameworkCore.InMemory? I mean, how can I reset change tracking when _context.SaveChanges() is called?
Viewing all 1698 articles
Browse latest View live


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