Answer the question
In order to leave comments, you need to log in
How to connect a database to an ASP.NET MVC web application in Visual Studio 2017?
I work with Entity Framework. There is a database placed in the App_Data folder - Database1.mdf. I create a model, context, controller.
namespace Test.Models
{
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public string Coach { get; set; }
}
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Position { get; set; }
public int? TeamId { get; set; }
public Team Team { get; set; }
}
public class Context : DbContext
{
public DbSet<Team> Teams { get; set; }
public DbSet<Player> Players { get; set; }
}
namespace Test.Controllers
{
public class HomeController : Controller
{
Context c = new Context();
public ActionResult Index()
{
var players = c.Players.Include(p => p.Team);
return View(players.ToList());
}
}
}
<connectionStrings>
<add name="Context" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\Database1.mdf';Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
System.Data.SqlClient.SqlException: "Cannot create file 'c:\users\alex\source\repos\Test\Test\App_Data\Database1.mdf' because it already exists. Change the file path or the file name, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors."
namespace MusicShopWeb
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
public partial class Buyers
{
public int Id { get; set; }
public string fio { get; set; }
public string address { get; set; }
public string phone { get; set; }
}
public class BuyersContext : DbContext
{
public DbSet<Buyers> Buyers { get; set; }
}
}
namespace MusicShopWeb.Controllers
{
public class Buyersontroller : Controller
{
private BuyersContext db = new BuyersContext();
public ActionResult Index()
{
return View(db.Buyers.ToList());
}
}
@model IEnumerable<MusicShopWeb.Buyers>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.fio)
</th>
<th>
@Html.DisplayNameFor(model => model.address)
</th>
<th>
@Html.DisplayNameFor(model => model.phone)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.fio)
</td>
<td>
@Html.DisplayFor(modelItem => item.address)
</td>
<td>
@Html.DisplayFor(modelItem => item.phone)
</td>
</tr>
}
</table>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question