I am trying to connect the data with SQL and Visual Studio C#, the databases are connected but my contents doesn’t seem in the SQL folders when I try to go SQL Studio. I’ve added Models and created migration but the problem occurs when I try to execute the app from IIS Express. Can the error occur because of unused classes in the models?
Controller
public class ProductsController : Controller
{
private readonly DataContext _context;
public ProductsController(DataContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var allProducts = await _context.Products.ToListAsync();
return View(allProducts);
}
}
AppDbInitializer.cs
public static void Seed(IApplicationBuilder applicationBuilder)
{
using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<DataContext>();
context.Database.EnsureCreated();
context.Products.AddRange(new List<Product>()
{
//charmlar
new Product()
{
ProductId=1,
ProductName="Kiraz Çiçeği Sallantılı Charm",
Image="~/img/flower.jpg",
Price=(int)2.519,
Description="925 ayar gümüşten üretilen Kiraz Çiçeği Sallantılı Charm’ımız ile baharın ilk işaretlerini kutla. Elde uygulanmış pembe ve beyaz mineye sahip; ışıltılı pembe kübik zirkon ile vurgulanıyor ve kiraz çiçeğimizin üzerindeki yapraklar rüzgârda savruluyormuşçasına hafifçe dönüyor. Pavé kaplamalı halka kısmı, bu olmazsa olmaz çiçek charm’a son dokunuşu yapıyor. Sıcak bir ilkbahar görünümü için diğer soğuk tonlu mücevherler ile kullanabilirsin.",
Characteristics="Doğa ve Gökyüzü temalıdır. Derinliği 6 mm,ağırlığı 12,6 mm, genişliği ise 13 mm'dir. Menşei Türkiye'dir.",
},
new Product()
{
ProductId=2,
ProductName="Sonsuz Kalp Klipsli Yılan Zincir Bileklik",
Image="~/img/snake.jpg",
Price=(int)2.519,
Description="Aileyi birbirine bağlayan sonsuz sevgiyi temsil eden Işıltılı Sonsuz Kalp Klipsli Yılan Zincir Bileklik senin için en önemli olanlar için anlamlı bir hediye. Kafes işi kalp klipsinde, kenarlarında taşlar ve kalbin etrafına yerleştirilmiş asimetrik bir sonsuzluk sembolü yer alıyor. Klipsin arkasında “Family forever and Always” yazısı bulunuyor. Bileklikte, onu üç bölüme ayıran iki diş (yükseltilmiş charm ayırıcılar) bulunmaktadır. Sevdiklerini simgeleyen 16-18 adede kadar favori charm veya sallantılı charm’larınla birlikte kullan veya kalbindeki birine hediye et.",
Characteristics="Şeffaf renkte, metal türü gümüştür. Derinliği 8 mm,ağırlığı 10,5 mm, genişliği 12,9 mm'dir. Menşei Türkiye'dir.",
},
});
context.SaveChanges();
context.Categories.AddRange(new List<Category>()
{
new Category()
{
CategoryName="Charm'lar",
CategoryId=1,
},
new Category()
{
CategoryName="Yüzükler",
CategoryId=2,
},
new Category()
{
CategoryName="Küpeler",
CategoryId=3,
},
new Category()
{
CategoryName="Kolyeler",
CategoryId=4,
},
});
context.SaveChanges();
DataContext.cs
public class DataContext:DbContext
{
public DataContext(DbContextOptions<DataContext>options) : base(options)
{
}
public DbSet<Account> Accounts => Set<Account>();
public DbSet<Address> Addresses => Set<Address>();
public DbSet<AddressNotebook> AddressNotebooks => Set<AddressNotebook>();
public DbSet<Basket> Baskets => Set<Basket>();
public DbSet<CartItem> CartItems => Set<CartItem>();
public DbSet<Category> Categories => Set<Category>();
public DbSet<Contact> Contacts => Set<Contact>();
public DbSet<CreditCard> CreditCards => Set<CreditCard>();
public DbSet<Customer> Customers => Set<Customer>();
public DbSet<CustomerPayment> CustomerPayments => Set<CustomerPayment>();
public DbSet<Discount> Discounts => Set<Discount>();
public DbSet<EditAcc> EditAccs => Set<EditAcc>();
public DbSet<Location> Locations => Set<Location>();
public DbSet<MainPage> MainPages => Set<MainPage>();
public DbSet<MyAccount> MyAccounts => Set<MyAccount>();
public DbSet<MyInfo> MyInfos => Set<MyInfo>();
public DbSet<OrderDetail> OrderDetails => Set<OrderDetail>();
public DbSet<OrderItem> OrderItems => Set<OrderItem>();
public DbSet<OrderPast> OrderPasts => Set<OrderPast>();
public DbSet<PaymentDetail> PaymentDetails => Set<PaymentDetail>();
public DbSet<Product> Products => Set<Product>();
public DbSet<ShoppingCart> ShoppingCarts => Set<ShoppingCart>();
}
View
@model IEnumerable<Product>
@{
ViewData["Title"] = "Mağaza";
}
<div class="row">
<div class="col-md-8 offset-md-2">
<table class="table">
<thead>
<tr class="text-center">
<th>@Html.DisplayNameFor(model => model.ProductName)</th>
<th>@Html.DisplayNameFor(model => model.Image)</th>
<th>@Html.DisplayNameFor(model => model.Description)</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td class="align-middle">
<img class="rounded-circle" src="@item.ProductName" alt="@item.Image" style="max-width: 150px" />
</td>
<td class="align-middle">
@Html.DisplayFor(modelItem => item.ProductName)
</td>
<td class="align-middle">
@Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<DataContext>(options =>
{
var config = builder.Configuration;
var connectionString = config.GetConnectionString("database");
options.UseSqlServer(connectionString);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
AppDbInitializer.Seed(app);
app.Run();
I’ve encountered a problem during running time after trying to seed my database, in fact I’ve written Appdbinitializer.Seed(app) in “Program.cs”, but it turns out to give a warning. Migration is completed with no problem, I am tring to see my data for both “Products” and “Categories” columns but it doesn’t appear. Whenever I try to open the IIS Express, I am getting this issue.