none
(newbie) Create a C# app that connects to SQL Server using the Entity Framework Core ORM in .NET Core RRS feed

  • Question

  •  Hi all, 

    I'm trying to follow a kind of "Hello world" tutorial from this link: https://www.microsoft.com/en-us/sql-server/developer-get-started/csharp/ubuntu/step/2.html

    It's step 2.2 Create a C# app that connects to SQL Server using the Entity Framework Core ORM in .NET Core

    (previous step 2.1 went well for me)

    Now I'm getting error: 

    user@pc:~/SqlServerEFSample$ dotnet restore
      Restore completed in 32,78 ms for /home/user/SqlServerEFSample/SqlServerEFSample.csproj.
    user@pc:~/SqlServerEFSample$ dotnet run
    Task.cs(11,24): error CS0246: The type or namespace name 'Users' could not be found (are you missing a using directive or an assembly reference?) [/home/user/SqlServerEFSample/SqlServerEFSample.csproj]
    EFSampleContext.cs(17,22): error CS0246: The type or namespace name 'User' could not be found (are you missing a using directive or an assembly reference?) [/home/user/SqlServerEFSample/SqlServerEFSample.csproj]
    
    The build failed. Fix the build errors and run again.
    Please advise how to fix it. See source files below.

    SqlServerEFSample.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp3.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
      </ItemGroup>
    
    </Project>


    Program.cs:

    using System;
    using System.Linq;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    
    namespace SqlServerEFSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("** C# CRUD sample with Entity Framework Core and SQL Server **\n");
                try
                {
                    // Build connection string
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                    builder.DataSource = "127.0.0.1";   // update me
                    builder.UserID = "user";              // update me
                    builder.Password = "password";      // update me
                    builder.InitialCatalog = "db";
    
                    using (EFSampleContext context = new EFSampleContext(builder.ConnectionString))
                    {
                        context.Database.EnsureDeleted();
                        context.Database.EnsureCreated();
                        Console.WriteLine("Created database schema from C# classes.");
    
                        // Create demo: Create a User instance and save it to the database
                        User newUser = new User { FirstName = "Anna", LastName = "Shrestinian" };
                        context.Users.Add(newUser);
                        context.SaveChanges();
                        Console.WriteLine("\nCreated User: " + newUser.ToString());
    
                        // Create demo: Create a Task instance and save it to the database
                        Task newTask = new Task() { Title = "Ship Helsinki", IsComplete = false, DueDate = DateTime.Parse("04-01-2017") };
                        context.Tasks.Add(newTask);
                        context.SaveChanges();
                        Console.WriteLine("\nCreated Task: " + newTask.ToString());
    
                        // Association demo: Assign task to user
                        newTask.AssignedTo = newUser;
                        context.SaveChanges();
                        Console.WriteLine("\nAssigned Task: '" + newTask.Title + "' to user '" + newUser.GetFullName() + "'");
    
                        // Read demo: find incomplete tasks assigned to user 'Anna'
                        Console.WriteLine("\nIncomplete tasks assigned to 'Anna':");
                        var query = from t in context.Tasks
                                    where t.IsComplete == false &&
                                    t.AssignedTo.FirstName.Equals("Anna")
                                    select t;
                        foreach(var t in query)
                        {
                            Console.WriteLine(t.ToString());
                        }
    
                        // Update demo: change the 'dueDate' of a task
                        Task taskToUpdate = context.Tasks.First(); // get the first task
                        Console.WriteLine("\nUpdating task: " + taskToUpdate.ToString());
                        taskToUpdate.DueDate = DateTime.Parse("06-30-2016");
                        context.SaveChanges();
                        Console.WriteLine("dueDate changed: " + taskToUpdate.ToString());
    
                        // Delete demo: delete all tasks with a dueDate in 2016
                        Console.WriteLine("\nDeleting all tasks with a dueDate in 2016");
                        DateTime dueDate2016 = DateTime.Parse("12-31-2016");
                        query = from t in context.Tasks
                                where t.DueDate < dueDate2016
                                select t;
                        foreach(Task t in query)
                        {
                            Console.WriteLine("Deleting task: " + t.ToString());
                            context.Tasks.Remove(t);
                        }
                        context.SaveChanges();
    
                        // Show tasks after the 'Delete' operation - there should be 0 tasks
                        Console.WriteLine("\nTasks after delete:");
                        List<Task> tasksAfterDelete = (from t in context.Tasks select t).ToList<Task>();
                        if (tasksAfterDelete.Count == 0)
                        {
                            Console.WriteLine("[None]");
                        }
                        else
                        {
                            foreach (Task t in query)
                            {
                                Console.WriteLine(t.ToString());
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
    
                Console.WriteLine("All done. Press any key to finish...");
                Console.ReadKey(true);
            }
        }
    }


    Task.cs:

    using System;
    
    namespace SqlServerEFSample
    {
        public class Task
        {
            public int TaskId { get; set; }
            public string Title { get; set; }
            public DateTime DueDate { get; set; }
            public bool IsComplete { get; set; }
            public virtual User AssignedTo { get; set; }
    
            public override string ToString()
            {
                return "Task [id=" + this.TaskId + ", title=" + this.Title + ", dueDate=" + this.DueDate.ToString() + ", IsComplete=" + this.IsComplete + "]";
            }
        }
    }

    EFSampleContext.cs:

    using Microsoft.EntityFrameworkCore;
    
    namespace SqlServerEFSample
    {
        public class EFSampleContext : DbContext
        {
            string _connectionString;
            public EFSampleContext(string connectionString)
            {
                this._connectionString = connectionString;
            }
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(this._connectionString);
            }
    
            public DbSet<User> Users { get; set; }
            public DbSet<Task> Tasks { get; set; }
        }
    }


    Friday, October 4, 2019 5:46 PM

Answers

  • The error message for Task.cs(11,24) says that Users (plural) cannot be found but the code you show for Task.cs has User (singular) so there is a mismatch. We cannot trust the code you posted.

    The error seems to be that there is no definition of the User class. You post code for the Task class but not the User class. Assuming there is not a definition of the User class anywhere in your code then you just need to add that.

    However references (allocations and such) of the User class appears in many places in your code and you are not getting errors for the class from the other places so that is confuting.



    Sam Hobbs
    SimpleSamples.Info


    • Edited by Simple Samples Friday, October 4, 2019 6:33 PM spelling
    • Marked as answer by marchelloua Saturday, October 5, 2019 8:06 AM
    Friday, October 4, 2019 6:32 PM

All replies

  • The error message for Task.cs(11,24) says that Users (plural) cannot be found but the code you show for Task.cs has User (singular) so there is a mismatch. We cannot trust the code you posted.

    The error seems to be that there is no definition of the User class. You post code for the Task class but not the User class. Assuming there is not a definition of the User class anywhere in your code then you just need to add that.

    However references (allocations and such) of the User class appears in many places in your code and you are not getting errors for the class from the other places so that is confuting.



    Sam Hobbs
    SimpleSamples.Info


    • Edited by Simple Samples Friday, October 4, 2019 6:33 PM spelling
    • Marked as answer by marchelloua Saturday, October 5, 2019 8:06 AM
    Friday, October 4, 2019 6:32 PM
  • Thanks Sam! 

    My bad, I was missing User.cs:

    using System;
    using System.Collections.Generic;
    
    namespace SqlServerEFSample
    {
        public class User
        {
            public int UserId { get; set; }
            public String FirstName { get; set; }
            public String LastName { get; set; }
            public virtual IList<Task> Tasks { get; set; }
    
            public String GetFullName()
            {
                return this.FirstName + " " + this.LastName;
            }
            public override string ToString()
            {
                return "User [id=" + this.UserId + ", name=" + this.GetFullName() + "]";
            }
        }
    }

    Also I had to fix date from 12-31-2016 into 2016-12-31 and other similar one as well.

    After mentioned fixed it went well.

    Thanks to all for your attention.

    Friday, October 4, 2019 6:55 PM
  • If my response helped you then please mark it as an answer.


    Sam Hobbs
    SimpleSamples.Info

    Friday, October 4, 2019 7:29 PM
  • Done, thanks.
    Saturday, October 5, 2019 8:06 AM