M
M
mr_blond972018-01-04 12:22:30
SQL
mr_blond97, 2018-01-04 12:22:30

How to get the number of rows in a table?

The base model from the example looks like this:

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace ConsoleApp.SQLite
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=blogging.db");
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}

You need to initialize the Blog[] blogs array and populate it with values ​​from db.Blogs. But in order to initialize the array, you need to find out how long it should be or how many rows are contained in db.Blogs, how to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Pavlov, 2018-01-04
@mr_blond97

If there is already data in the DbSet, then you can get an array like this:
If you need to explicitly count the records, you can execute a scalar like this :

var command = new SQLiteCommand(connection);
command.CommandText = "SELECT COUNT(Id) FROM Blogs";
command.CommandType = CommandType.Text;
int сount = (int) command.ExecuteScalar();
Blog[] blogs = new Blogs[count];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question