mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-05-15 07:34:46 +00:00
Upload of pre-existing files
This commit is contained in:
commit
4c21152830
150 changed files with 730703 additions and 0 deletions
113
.NET/Database/ADO.NET.md
Normal file
113
.NET/Database/ADO.NET.md
Normal file
|
@ -0,0 +1,113 @@
|
|||
# [ADO.NET](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ "ADO.NET Docs")
|
||||
|
||||
`ADO.NET` is a set of classes that expose data access services for .NET.
|
||||
The `ADO.NET` classes are found in `System.Data.dll`, and are integrated with the XML classes found in `System.Xml.dll`.
|
||||
|
||||
[ADO.NET provider for SQLite](https://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki "System.Data.SQLite")
|
||||
|
||||
## [Connection Strings](https://www.connectionstrings.com)
|
||||
|
||||
### [SQL Server 2019](https://www.connectionstrings.com/sql-server-2019/)
|
||||
|
||||
- Standard Security:
|
||||
- `Server=<server_name>; Database=<database>; UID=<user>; Pwd=<password>;`
|
||||
- `Server=<server_name>; Database=<database>; User ID=<user>; Password=<password>;`
|
||||
- `Data Source=<server_name>; Initial Catalog=<database>; UID=<user>; Pwd=<password>;`
|
||||
- Specific Instance: `Server=<server_name>\<instance_name>; Database=<database>; User ID=<user>; Password=<password>;`
|
||||
- Trusted Connection (WinAuth): `Server=<server_name>; Database=<database>; Trusted_Connection=True;`
|
||||
- MARS: `Server=<server_name>; Database=<database>; Trusted_Connection=True; MultipleActiveResultSets=True;`
|
||||
|
||||
**NOTE**: *Multiple Active Result Sets* (MARS) is a feature that works with SQL Server to allow the execution of multiple batches on a single connection.
|
||||
|
||||
### [SQLite](https://www.connectionstrings.com/sqlite/)
|
||||
|
||||
- Basic: `Data Source: path\to\db.sqlite3; Version=3;`
|
||||
- In-Memory Dataabse: `Data Source=:memory:; Version=3; New=True`
|
||||
- With Password: `Data Source: path\to\db.sqlite3; Version=3; Password=<password>`
|
||||
|
||||
## Connection to DB
|
||||
|
||||
```cs
|
||||
using System;
|
||||
using System.Data.SqlClient; // ADO.NET Provider, installed through NuGet
|
||||
|
||||
namespace <namespace>
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
// Connection to SQL Server DBMS
|
||||
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();
|
||||
connectionString.DataSource = "<server_name>";
|
||||
connectionString.UserID = "<user>";
|
||||
connectionString.Password = "<password>";
|
||||
connectionString.InitialCatalog = "<database>";
|
||||
|
||||
// more compact
|
||||
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder("Server=<server_name>;Database=<database>;UID=<user>;Pwd=<password>")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## DB Interrogation
|
||||
|
||||
### `SqlConnection`
|
||||
|
||||
```cs
|
||||
using (SqlConnection connection = new SqlConnection())
|
||||
{
|
||||
connection.ConnectionString = connectionString.ConnectionString;
|
||||
connection.Open(); // start comunication w/ sql server
|
||||
}
|
||||
|
||||
// more compact
|
||||
using (SqlConnection connection = new SqlConnection(connectionString)) {
|
||||
connection.Open()
|
||||
}
|
||||
```
|
||||
|
||||
### [SqlCommand](https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand)
|
||||
|
||||
```cs
|
||||
string sql = "<sql_instruction>";
|
||||
|
||||
using (SqlCommand command = new SqlCommand())
|
||||
{
|
||||
command.Connection = connection; // SqlConnection
|
||||
command.CommandText = "... @Parameter"; // or name of StoredProcedure
|
||||
|
||||
// add parameters to the SqlParameterCollection, WARNING: table names or columns cannot be parameters
|
||||
command.Parameters.Add("@Parameter", SqlDbType.<DBType>, columnLength).Value = value;
|
||||
command.Parameters.AddWithValue("@Parameter", value);
|
||||
command.Parameters.AddWithValue("@Parameter", (object) value ?? DBNull.Value); // if Parameter is nullable
|
||||
|
||||
// Create an instance of a SqlParameter object.
|
||||
command.CreateParameter();
|
||||
|
||||
command.CommandType = CommandType.Text; // or StoredProcedure
|
||||
|
||||
int affectedRows = command.ExecuteNonQuery(); // execute the query and return the number of affected rows
|
||||
}
|
||||
```
|
||||
|
||||
### `SqlDataReader`
|
||||
|
||||
```cs
|
||||
using (SqlDataReader cursor = command.ExecuteReader()) // object to get data from db
|
||||
{
|
||||
while (cursor.Read()) // get data till possible
|
||||
{
|
||||
// preferred methodology
|
||||
cursor["<column_name>"].ToString(); // retrieve data form the column
|
||||
cursor[<column_index>].ToString(); // retrieve data form the column
|
||||
|
||||
// check for null before retrieving the value
|
||||
if(!cursor.IsDBNull(n))
|
||||
{
|
||||
sqlreader.Get<SystemType>(index); // retrieve data form the n-th column
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
203
.NET/Database/EntityFramework.md
Normal file
203
.NET/Database/EntityFramework.md
Normal file
|
@ -0,0 +1,203 @@
|
|||
# Entity Framework
|
||||
|
||||
## Model & Data Annotations
|
||||
|
||||
```cs
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
|
||||
namespace <Project>.Model
|
||||
{
|
||||
public class Entity
|
||||
{
|
||||
[Key] // set as PK (Id & EntityId are automatically detected to be PKs)
|
||||
public int Id { get; set; }
|
||||
|
||||
[Required]
|
||||
public Type ForeignObject { get; set; } // Not Null in DB
|
||||
public Type ForeignObject { get; set; } // Allow Null in DB
|
||||
|
||||
public int Prop { get; set; } // Not Null in DB (primitive are not nullable)
|
||||
public int? Prop { get; set; } // Allow Null in DB
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Context
|
||||
|
||||
NuGet Packages to install:
|
||||
|
||||
- `Microsoft.EntityFrameworkCore`
|
||||
- `Microsoft.EntityFrameworkCore.Tools` to use migrations
|
||||
- `Microsoft.EntityFrameworkCore.Design` *or* `Microsoft.EntityFrameworkCore.<db_provider>.Design` needed for tools to work (bundled w\ tools)
|
||||
- `Microsoft.EntityFrameworkCore.<db_provider>`
|
||||
|
||||
```cs
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace <Project>.Model
|
||||
{
|
||||
class Context : DbContext
|
||||
{
|
||||
public Context(DbContextOptions options) : base(options)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
class Context : DbContext
|
||||
{
|
||||
private const string _connectionString = "Server=<server_name>;Database=<database>;UID=<user>;Pwd=<password>";
|
||||
|
||||
// connect to db
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.UseSqlServer(_connectionString); // specify connection
|
||||
}
|
||||
|
||||
//DBSet<TEntity> represents the collection of all entities in the context (or that can be queried from the database) of a given type
|
||||
public DbSet<Entity> Entities { get; set; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Migrations
|
||||
|
||||
Create & Update DB Schema if necessary.
|
||||
|
||||
In Packge Manager Shell:
|
||||
|
||||
```ps1
|
||||
PM> Add-Migration <migration_name>
|
||||
PM> update-database [-Verbose] # use the migrations to modify the db, -Verbose to show SQL queries
|
||||
```
|
||||
|
||||
In dotnet cli:
|
||||
|
||||
```ps1
|
||||
dotnet tool install --global dotnet-ef # if not already installed
|
||||
|
||||
dotnet ef migrations add <migration_name>
|
||||
dotnet ef database update
|
||||
```
|
||||
|
||||
## CRUD
|
||||
|
||||
### Create
|
||||
|
||||
```cs
|
||||
public static bool InsertOne(Entity entity)
|
||||
{
|
||||
int rows = 0;
|
||||
|
||||
using(var context = new Context())
|
||||
{
|
||||
context.Add(entity);
|
||||
context.SaveChanges();
|
||||
}
|
||||
|
||||
return rows == 1;
|
||||
}
|
||||
|
||||
public static bool InsertMany(IEnumerable<Entity> entities)
|
||||
{
|
||||
int rows = 0;
|
||||
|
||||
using(var context = new Context())
|
||||
{
|
||||
context.AddRange(entities);
|
||||
context.SaveChanges();
|
||||
}
|
||||
|
||||
return rows == entities.Count();
|
||||
}
|
||||
```
|
||||
|
||||
### Read
|
||||
|
||||
[Referenced Object Not Loading Fix](https://stackoverflow.com/a/5385288)
|
||||
|
||||
```cs
|
||||
public static List<Entity> SelectAll()
|
||||
{
|
||||
using(var context = new Context())
|
||||
{
|
||||
return context.Entities.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
static Entity SelectOneById(int id)
|
||||
{
|
||||
using(var context = new Context())
|
||||
{
|
||||
return context.Entities.Find(id);
|
||||
|
||||
// force read of foreign key identifying referenced obj
|
||||
return context.Entities.Include(c => c.ForeignObject).Find(id);
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Update
|
||||
|
||||
```cs
|
||||
public static bool UpdateOne(Entity entity)
|
||||
{
|
||||
int rows = 0;
|
||||
|
||||
using(var context = new Context())
|
||||
{
|
||||
context.Entities.Update(entity);
|
||||
context.SaveChanges();
|
||||
}
|
||||
|
||||
return rows == 1;
|
||||
}
|
||||
|
||||
public static bool UpdateMany(IEnumerable<Entity> entities)
|
||||
{
|
||||
int rows = 0;
|
||||
|
||||
using(var context = new Context())
|
||||
{
|
||||
context.UpdateRange(entities);
|
||||
context.SaveChanges();
|
||||
}
|
||||
|
||||
return rows == entities.Count();
|
||||
}
|
||||
```
|
||||
|
||||
### Delete
|
||||
|
||||
```cs
|
||||
public static bool DeleteOne(Entity entity)
|
||||
{
|
||||
int rows = 0;
|
||||
|
||||
using(var context = new Context())
|
||||
{
|
||||
context.Entities.Remove(entity);
|
||||
context.SaveChanges();
|
||||
}
|
||||
|
||||
return rows == 1;
|
||||
}
|
||||
|
||||
public static bool DeleteMany(IEnumerable<Entity> entities)
|
||||
{
|
||||
int rows = 0;
|
||||
|
||||
using(var context = new Context())
|
||||
{
|
||||
context.RemoveRange(entities);
|
||||
context.SaveChanges();
|
||||
}
|
||||
|
||||
return rows == entities.Count();
|
||||
}
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue