I am trying to implement an e-commerce website by following a course on Udemy. I am trying to update my database. I create a new table, called ProductCategories, which allows many-to-many relationship between Products and Categories. The problem is that my code generates the table, and adds the products to Product table, however, it cannot fill the ProductCategories table.
Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace shopapp.entity
{
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<ProductCategory> ProductCategories { get; set; }
}
}
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace shopapp.entity
{
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public bool IsApproved { get; set; }
public int CategoryId { get; set; }
public List<ProductCategory> ProductCategories { get; set; }
}
}
ProductCategory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace shopapp.entity
{
public class ProductCategory
{
public int CategoryId { get; set; }
public Category Category { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
}
DbContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using shopapp.entity;
namespace shopapp.data.Concrete.EfCore
{
public class ShopContext:DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// TODO
// check MySql version
optionsBuilder.UseMySQL("Server=localhost;port=3306;Database=shopapp2;Uid=root;Pwd=admin;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductCategory>()
.HasOne(pc => pc.Category)
.WithMany(pc => pc.ProductCategories)
.HasForeignKey(pc => pc.ProductId);
modelBuilder.Entity<ProductCategory>()
.HasOne(pc => pc.Product)
.WithMany(pc => pc.ProductCategories)
.HasForeignKey(pc => pc.CategoryId);
}
}
}
SeedDatabse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using shopapp.entity;
namespace shopapp.data.Concrete.EfCore
{
public static class SeedDatabase
{
public static void Seed()
{
using(var context = new ShopContext())
{
Console.WriteLine(context.Database.GetPendingMigrations().Count());
if (context.Database.GetPendingMigrations().Count() == 0)
{
Console.WriteLine(context.Categories.Count());
Console.WriteLine(context.Products.Count());
if (context.Categories.Count() == 0)
{
context.Categories.AddRange(Categories);
Console.WriteLine("Categories added!");
//Console.WriteLine("Products and ProductCategories added!");
}
if (context.Products.Count() == 0)
{
context.Products.AddRange(Products);
context.AddRange(ProductCategories); // we do not need to specify Product or category
}
context.SaveChanges();
}
}
}
private static Category[] Categories = {
new Category(){ CategoryId=4, Name = "Fashion", Description="Fashion Category"},
new Category(){ CategoryId=5, Name = "Supermarket", Description="Supermarket Category"},
new Category(){ CategoryId=6, Name = "Mom and Baby", Description="Mom and Baby Category"}
};
private static Product[] Products = {
new Product(){ProductId=11, Name = "Test Product 1", Price=1000, Description="Test Data", ImageUrl="test.jpg", IsApproved=true},
new Product(){ProductId=12, Name = "Test Product 2", Price=1200, Description="Test Data", ImageUrl="test.jpg", IsApproved=true},
new Product(){ProductId=13, Name = "Test Product 3", Price=1400, Description="Test Data", ImageUrl="test.jpg", IsApproved=false}
};
private static ProductCategory[] ProductCategories =
{
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]}
};
}
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using shopapp.business.Abstract;
using shopapp.business.Concrete;
using shopapp.data.Abstract;
using shopapp.data.Concrete.EfCore;
namespace shopapp.webui
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// IProductRepository'yi uygulama çağırıldığı zaman EfCoreProductRepository nesne oluşturulup gönderilecek.
services.AddScoped<IProductRepository,EfCoreProductRepository>();
services.AddScoped<IProductService,ProductManager>();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// checks if the app is in development process
// Call your Seed method
// env is a global variable, you can change this in
// /shopapp\\.vscode\\launch.json file
// by changing
/*
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
*/
// to
/*"env": {
"ASPNETCORE_ENVIRONMENT": "Production"
},*/
// when you publish your website
if (env.IsDevelopment())
{
SeedDatabase.Seed();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "products",
pattern: "products/{category?}",
defaults: new {controller="Shop", action="list"}
);
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
I am using .Net 7.0.102.
you have register your dbcontext
Services.AddDbContext();
Db Seed Code must be changed this way. as you seed class creating a blank Dbcontext when you running.
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService();
context.Database.EnsureCreated();
DbInitializer.Initialize(context);
}
In your Product class , CategoryId property not require as you want to define many to many relation.
Product and Category Class need to this attribute if you got an error for primary key.
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ProductId { get; set; }
you will also get a warning for ProductCategory as there is no primary key.
optionally you can add
public DbSet<ProductCategory> ProductCategories { get; set; }
if need direct access to this table.
for more see the documentation here
https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-7.0&tabs=visual-studio
Related
I have simple project to show the problem, I want to connect ICollection<Post> with view View_BlogPosts. This is just simplified scenario, in real live i need to connect entity with big View with many columns from different tables.
The most interesting part of code is: OnModelCreating(ModelBuilder modelBuilder) where there is configuration View with Entity: Post (One Blog to Many Posts). But its not working now, this line of code: var test = db.BlogWithPosts.ToList(); returns empty collection of Posts.
How to fix this?
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Samples
{
public class Program
{
private static void Main()
{
SetupDatabase();
using (var db = new BloggingContext())
{
var test = db.BlogWithPosts.ToList();
}
}
private static void SetupDatabase()
{
using (var db = new BloggingContext())
{
if (db.Database.EnsureCreated())
{
db.Blogs.Add(
new Blog
{
Name = "Fish Blog",
Url = "http://sample.com/blogs/fish",
Posts = new List<Post>
{
new Post { Title = "Fish care 101" },
new Post { Title = "Caring for tropical fish" },
new Post { Title = "Types of ornamental fish" }
}
});
db.Blogs.Add(
new Blog
{
Name = "Cats Blog",
Url = "http://sample.com/blogs/cats",
Posts = new List<Post>
{
new Post { Title = "Cat care 101" },
new Post { Title = "Caring for tropical cats" },
new Post { Title = "Types of ornamental cats" }
}
});
db.Blogs.Add(
new Blog
{
Name = "Catfish Blog",
Url = "http://sample.com/blogs/catfish",
Posts = new List<Post>
{
new Post { Title = "Catfish care 101" }, new Post { Title = "History of the catfish name" }
}
});
db.SaveChanges();
db.Database.ExecuteSqlRaw(
#"CREATE VIEW View_BlogPosts AS
SELECT b.Name , b.BlogId, b.Url FROM Blogs b");
}
}
}
}
public class BloggingContext : DbContext
{
private static readonly ILoggerFactory _loggerFactory
= LoggerFactory.Create(
builder => builder.AddConsole().AddFilter((c, l) => l == LogLevel.Information && !c.EndsWith("Connection")));
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<BlogWithPosts> BlogWithPosts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(
// #"Server=(localdb)\mssqllocaldb;Database=Sample.KeylessEntityTypes;Trusted_Connection=True;ConnectRetryCount=0;")
#"Server=.\SQLEXPRESS;Database=test_view;Trusted_Connection=True;")
.UseLoggerFactory(_loggerFactory);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BlogWithPosts>(eb =>
{
//eb.HasNoKey();
eb.ToView("View_BlogPosts");
eb.HasKey(bwp => bwp.BlogId);
eb.Property(v => v.BlogName).HasColumnName("Name");
eb
.HasMany(bwp => bwp.Posts)
.WithOne()
.HasForeignKey(p => p.BlogId);
});
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<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 class BlogWithPosts
{
public int BlogId { get; set; }
public string BlogName { get; set; }
public ICollection<Post> Posts { get; set; } = new List<Post>();
}
}
EDIT :
Thanks #Neil W for answer:
It is good point but after var test = db.BlogWithPosts.Include(bwp => bwp.Posts).ToList(); there is still no Posts.
I have checked Database after run program and in Post table I find out, that there is second Id added:BlogId1
I have filled BlogId column same as BlogId1 like this:
and posts appeared
But how to set configuration that second id: BlogId1 will not appear.
You need to ask for the related entities when accessing the context, using Include:
var test = db.BlogWithPosts.Include(bwp => bwp.Posts).ToList();
Thanks for all answers and comments. As #atiyar point there should be explicitly relation between Post and Blog which stops creating BlogId1 column. So working example is like below:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Samples
{
public class Program
{
private static void Main()
{
SetupDatabase();
using (var db = new BloggingContext())
{
var test = db.BlogWithPosts.Include(bp => bp.Posts).ToList();
}
}
private static void SetupDatabase()
{
using (var db = new BloggingContext())
{
if (db.Database.EnsureCreated())
{
db.Blogs.Add(
new Blog
{
Name = "Fish Blog",
Url = "http://sample.com/blogs/fish",
Posts = new List<Post>
{
new Post { Title = "Fish care 101" },
new Post { Title = "Caring for tropical fish" },
new Post { Title = "Types of ornamental fish" }
}
});
db.Blogs.Add(
new Blog
{
Name = "Cats Blog",
Url = "http://sample.com/blogs/cats",
Posts = new List<Post>
{
new Post { Title = "Cat care 101" },
new Post { Title = "Caring for tropical cats" },
new Post { Title = "Types of ornamental cats" }
}
});
db.Blogs.Add(
new Blog
{
Name = "Catfish Blog",
Url = "http://sample.com/blogs/catfish",
Posts = new List<Post>
{
new Post { Title = "Catfish care 101" }, new Post { Title = "History of the catfish name" }
}
});
db.SaveChanges();
db.Database.ExecuteSqlRaw(
#"CREATE VIEW View_BlogPosts AS
SELECT b.Name , b.BlogId, b.Url FROM Blogs b");
}
}
}
}
public class BloggingContext : DbContext
{
private static readonly ILoggerFactory _loggerFactory
= LoggerFactory.Create(
builder => builder.AddConsole().AddFilter((c, l) => l == LogLevel.Information && !c.EndsWith("Connection")));
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<BlogWithPosts> BlogWithPosts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(
// #"Server=(localdb)\mssqllocaldb;Database=Sample.KeylessEntityTypes;Trusted_Connection=True;ConnectRetryCount=0;")
#"Server=.\SQLEXPRESS;Database=test_view;Trusted_Connection=True;")
.UseLoggerFactory(_loggerFactory);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BlogWithPosts>(eb =>
{
//eb.HasNoKey();
eb.ToView("View_BlogPosts");
eb.HasKey(bwp => bwp.BlogId);
eb.Property(v => v.BlogName).HasColumnName("Name");
eb
.HasMany(bwp => bwp.Posts)
.WithOne()
.HasForeignKey(p => p.BlogId);
});
modelBuilder.Entity<Blog>(blog =>
{
blog.HasMany(bwp => bwp.Posts)
.WithOne(b => b.Blog)
.HasForeignKey(p => p.BlogId);
});
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<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; }
}
public class BlogWithPosts
{
public int BlogId { get; set; }
public string BlogName { get; set; }
public ICollection<Post> Posts { get; set; } = new List<Post>();
}
}
What is important this example was tested on EF Core 5.0.2
I am following a tutorial on the documentation to try create my own database. The data was seeding properly with 3 tables and now I have added 6 I can't get the data to seed. I have tried creating a migration and updating the database. I did change some of the ON DELETE CASCADE to ON DELETE NO ACTION as I was getting an error with cascading and I am not sure if that is the reason that it isn't seeding.
For reference it was the tables 'Car' , 'PaymentPlan' & 'SalesMan' that was working previously
Initialise code:
using GarageSales.Data;
using GarageSales.Models;
using System;
using System.Linq;
namespace GarageSales.Data
{
public static class DbInitializer
{
public static void Initialize(GarageSalesContext context)
{
//context.Database.EnsureCreated();
// Look for any Cars.
if (context.Cars.Any())
{
return; // DB has been seeded
}
var Customers = new Customer[]
{
new Customer{FirstName="Ray", LastName="Easton", Gender="Male", Address="2 Church Road", PostCode="BT35 0JW", RentalID=1, CarID=1, SalesManID=1},
new Customer{FirstName="Amelie", LastName="Bush", Gender="Female", Address="54 Beach Gardens", PostCode="BT34 0JE", RentalID=2, CarID=2, SalesManID=2},
new Customer{FirstName="Ray", LastName="Easton", Gender="Male", Address="2 Church Road", PostCode="BT67 0JW", RentalID=3, CarID=3, SalesManID=3}
};
foreach (Customer customer in Customers)
{
context.Customer.Add(customer);
}
context.SaveChanges();
var Cars = new Car[]
{
new Car{Model="I8",Manufacturer="BMW",EngineSize="1.5 L 3-cylinder"},
new Car{Model="A5",Manufacturer="Audi",EngineSize="5.2 L V10"},
new Car{Model="R8",Manufacturer="Audi",EngineSize="1.5 L 3-cylinder"}
};
foreach (Car car in Cars)
{
context.Cars.Add(car);
}
context.SaveChanges();
var SalesMen = new SalesMan[]
{
new SalesMan{FirstName="Darren",SurName="Dooning"},
new SalesMan{FirstName="Jim",SurName="Campbell"},
new SalesMan{FirstName="Jade",SurName="Mull"},
};
foreach (SalesMan SalesMan in SalesMen)
{
context.SalesMen.Add(SalesMan);
}
context.SaveChanges();
var Rentals = new Rental[]
{
new Rental{Price=150, Duration=36, Quote=3500, CustomerID=1, CarID=1, SalesManID=1},
new Rental{Price=200, Duration=24, Quote=2000, CustomerID=2, CarID=2, SalesManID=2},
new Rental{Price=400, Duration=12, Quote=4500, CustomerID=3, CarID=3, SalesManID=3}
};
foreach (Rental Rental in Rentals)
{
context.Rental.Add(Rental);
}
context.SaveChanges();
var PaymentPlans = new PaymentPlan[]
{
new PaymentPlan{CarID=1,SalesManID=1},
new PaymentPlan{CarID=2,SalesManID=2},
new PaymentPlan{CarID=3,SalesManID=3}
};
foreach (PaymentPlan PaymentPlan in PaymentPlans)
{
context.PaymentPlans.Add(PaymentPlan);
}
context.SaveChanges();
var Duration = new Duration[]
{
new Duration{DurationLength=36, RentalID=1, SalesManID=1},
new Duration{DurationLength=24, RentalID=2, SalesManID=2},
new Duration{DurationLength=12, RentalID=3, SalesManID=3}
};
foreach (Duration duration in Duration)
{
context.Duration.Add(duration);
}
context.SaveChanges();
}
}
}
Context class (The dataSets are 2 different ways as I figured late on and would have to go and change it to make the program run):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using GarageSales.Models;
namespace GarageSales.Data
{
public class GarageSalesContext: DbContext
{
public GarageSalesContext (DbContextOptions<GarageSalesContext> options)
: base(options)
{
}
public DbSet<Car> Cars { get; set; }
public DbSet<PaymentPlan> PaymentPlans { get; set; }
public DbSet<SalesMan> SalesMen { get; set; }
public DbSet<GarageSales.Models.Customer> Customer { get; set; }
public DbSet<GarageSales.Models.Duration> Duration { get; set; }
public DbSet<GarageSales.Models.Rental> Rental { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>().ToTable("Car");
modelBuilder.Entity<PaymentPlan>().ToTable("PaymentPlan");
modelBuilder.Entity<SalesMan>().ToTable("SalesMan");
modelBuilder.Entity<Duration>().ToTable("Duration");
modelBuilder.Entity<Rental>().ToTable("Rental");
modelBuilder.Entity<Customer>().ToTable("Customer");
}
}
}
If you need anymore information just ask
i'm trying to learn how to create Web Api, and i have an error.
I don't know what to do, first it required to use sufix M when i used it, VS show me error:
You cannnot implicitly convert "RESTfullApi.Models.Product []" to
"RESTfullApi.Models.Product"
I was trying to find answer on the internet but nothing explain this case.
Maybe you know what is wrong with it?
This is tutorial in which i practice:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
ProductsController.cs
using RESTfullApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace RESTfullApi.Controllers
{
public class ProductsController : ApiController
{
Product products = new Product[]
{
new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
}
}
Product.cs (Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RESTfullApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
Message is self explanatory. Change products to
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
};
i have a Problem with my SQLite-Database. I use the SQLite.Net and SQLiteNetExtensions PCL NuGets and followed this excample: Link
I have a connection and it insert a stock but not the valuation list.
My copy paste code:
var valuation1 = new Valuation
{
Price = 15,
Time = DateTime.Now,
};
var valuation2= new Valuation
{
Price = 22,
Time = DateTime.Now,
};
var euro = new Stock
{
Symbol = "€",
Valuations = new List<Valuation> { valuation1, valuation2 }
};
connection.CreateTable<Stock>();
connection.CreateTable<Valuation>();
connection.InsertWithChildren(euro);
var stockList = c.GetAllWithChildren<Stock>();
In Stocklist is a Stock but in Stock is no Valuation :(
usings:
using System; using System.Collections.Generic;
using System.Linq;
using SQLiteNetExtensions.Extensions;
using TestSQLite.Models;
Models:
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
using System;
using System.Collections.Generic;
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
[OneToMany] // One to many relationship with Valuation
public List<Valuation> Valuations { get; set; }
}
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
using System;
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Stock))] // Specify the foreign key
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
[ManyToOne] // Many to one relationship with Stock
public Stock Stock { get; set; }
}
Any ideas or suggestions what i could do to make it work?
EDIT:
I just tried some things and if i inseret it by my self like this:
c.Insert(euro);
var e = c.Find<Stock>(s => s.Symbol == "€");
var valuation1 = new Valuation
{
Price = 15,
Time = DateTime.Now,
StockId = e.StockId,
Stock = e
};
var valuation2 = new Valuation
{
Price = 22,
Time = DateTime.Now,
StockId = e.StockId,
Stock = e
};
c.Insert(valuation1);
c.Insert(valuation2);
var stockList = c.GetAllWithChildren<Stock>();
i get a correct stock "euro" and valutations in it! What is my mistake at InsertWithChildren? Or is there anything wrong with my models?
Hi there I have 2 classes called SlownikRyzyk and Ryzyko. I create new variable called query. I want to insert to query only those records from SlownikRyzyk which have relation with the records in Class Ryzyko. I found the way how to do that by using pure linq but I want to know how to do this with lambda expression.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqTraining
{
class SlownikRyzyk
{
public int Id { get; set; }
public string NazwaRyzyka { get; set; }
public static List<SlownikRyzyk> getListSlownikRyzyk()
{
List<SlownikRyzyk> listSlownikRyzyk = new List<SlownikRyzyk>
{
new SlownikRyzyk
{
Id=1,
NazwaRyzyka="Włamanie"
},
new SlownikRyzyk
{
Id=2,
NazwaRyzyka="Napad"
},
new SlownikRyzyk
{
Id=3,
NazwaRyzyka="Pożar"
},
new SlownikRyzyk
{
Id=4,
NazwaRyzyka="Zepsute zamki"
}
};
return listSlownikRyzyk;
}
}
class Ryzyko
{
public int Id { get; set; }
public string Opis { get; set; }
public int SlownikRyzykId { get; set; }
public static List<Ryzyko> getListRyzyko()
{
List<Ryzyko> listRyzyko = new List<Ryzyko>
{
new Ryzyko
{
Id=11,
Opis="Pożar piwnicy może grozić stratą wielu ton papieru",
SlownikRyzykId=3
},
new Ryzyko
{
Id=12,
Opis="Ktoś może zatrzasnąć się w pokuju",
SlownikRyzykId=0
},
new Ryzyko
{
Id=14,
Opis="Ktoś może napaść na kase",
SlownikRyzykId=0
},
new Ryzyko
{
Id=17,
Opis="Przez włamanie do biur mogą zostać wykradzione pufne dane frimy",
SlownikRyzykId=1
}
};
return listRyzyko;
}
}
class Program
{
static void Main(string[] args)
{
var query = from r in Ryzyko.getListRyzyko()
from s in SlownikRyzyk.getListSlownikRyzyk()
where s.Id == r.SlownikRyzykId
select s;
foreach (var a in query)
{
Console.WriteLine(a.NazwaRyzyka);
}
}
}
}
Try like this
var query=Ryzyko.getListRyzyko().
Join(SlownikRyzyk.getListSlownikRyzyk(),
r=>r.SlownikRyzykId,
s=>s.Id,
(r,s)=> new {R=r,S=s} )