Skip to content

Instantly share code, notes, and snippets.

@Rudyzio
Rudyzio / data.service.ts
Created January 24, 2019 16:22
Angular 7 abstract data service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SimpleModel } from '../models/common/SimpleModel';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService<T extends SimpleModel> {
public class Ingredient : BaseEntity
{
public string Name { get; set; }
public int Amount { get; set; }
[ForeignKey("Recipe")]
public int RecipeId { get; set; }
public Recipe Recipe { get; set; }
}
public class Recipe : BaseEntity
{
public string Name { get; set; }
public string Description { get; set; }
public string ImagePath { get; set; }
public RecipeDifficulty Difficulty { get; set; }
public int Time { get; set; }
public IEnumerable<Ingredient> Ingredients { get; set; }
public class User : BaseEntity
{
public string Name { get; set; }
public string Email { get; set; }
public IEnumerable<Recipe> Recipes { get; set; }
}
"ConnectionStrings":
{
"DatabaseConnection": "Server=(localdb)\mssqllocaldb;Database=MyCookingMaster;Trusted_Connection=True"
}
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Recipe> Recipes { get; set; }
public virtual DbSet<Ingredient> Ingredients { get; set; }
}
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(@Directory.GetCurrentDirectory() + "/../MyCookingMaster.API/appsettings.json").Build();
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
var connectionString = configuration.GetConnectionString("DatabaseConnection");
builder.UseSqlServer(connectionString);
return new ApplicationDbContext(builder.Options);
}
public class DataSeeder
{
public static void Initialize(ApplicationDbContext context)
{
if (!context.Users.Any())
{
var users = new List<User>()
{
new User { /*Id = 1,*/ Name = "John", Email = "john@john.com" },
new User { /*Id = 2,*/ Name = "Michael", Email = "michael@michael.com" }
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
}