Here is an example for reading not using a setup done in a form
public static async Task<DataSet> GetDataSet()
{
DataSet dataSet = new ();
await using var cn = new OleDbConnection { ConnectionString = ConnectionString };
await using var cmd = new OleDbCommand() { Connection = cn };
cmd.CommandText = "SELECT EmployeeID, FirstName, LastName FROM Employees";
await cn.OpenAsync();
DataTable table = new ("EmployeeTable");
table.Load(cmd.ExecuteReader());
dataSet.Tables.Add(table);
return dataSet;
}
Caller
private async void ReadDatSetButton_Click(object sender, EventArgs e)
{
await Task.Run(async () =>
{
DataSet dataSet = await EmployeesOperations.GetDataSet();
DataTable employeeTable = dataSet.Tables["EmployeeTable"];
foreach (DataRow row in employeeTable.Rows)
{
Debug.WriteLine($"{string.Join(",", row.ItemArray)}");
}
});
}
And EF Core is even better, requires the following package. Using Microsoft's common model, blog with post.
Main model - by using model name + Id EF uses it for the primary key, otherwise you need to tell EF via a configuration.
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
public override string ToString() => BlogId.ToString();
}
Child model, same thing with the primary key
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; }
public override string ToString() => Title;
}
The following uses SQL-Server, change UseSqlServer to whatever the access provider uses.
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
"Server=(localdb)\\mssqllocaldb;" +
"Database=EFSaving.RelatedData;Trusted_Connection=True");
}
}
Create the database in code
using (var context = new BloggingContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
Add some data
using (var context = new BloggingContext())
{
var blog = new Blog
{
Url = "http://blogs.msdn.com/dotnet",
Posts = new List<Post>
{
new() { Title = "Intro to C#" },
new() { Title = "Intro to VB.NET" },
new() { Title = "Intro to F#" }
}
};
context.Blogs.Add(blog);
Console.WriteLine($"{context.SaveChanges()}");
}
Read data
foreach (var item in context.Blogs.ToList())
{
Console.WriteLine($"{item.BlogId}");
foreach (var postItem in item.Posts)
{
Console.WriteLine($"\t{postItem.Title}");
}
}