C
C#17mo ago
Vyrania

❔ Database with SQL (coming from a Rails background)

So for those that don't know Rails, we generate our model like this rails g model product name:string (just one attribute for the example) Then in the console we go rails db:migrate once the database is migrated, we enter the Rails console and start populating it. Here's an example. Product.create(name: "Sweater") Lo and behold. That just created a new product called "Sweater" and it's now in the database. My question is can you do the same thing in the console with C# and ASP.NET?
7 Replies
Angius
Angius17mo ago
With EF Core, sure It's a little bit more involved, but also lets you just not write any SQL 1. Create a class that describes your model
public class Person
{
public int Id { get; set; }
public required string Name { get; set; }
public required DateOnly Birthday { get; set; }
}
public class Person
{
public int Id { get; set; }
public required string Name { get; set; }
public required DateOnly Birthday { get; set; }
}
2. Add the DbSet to your DbContext
public class MyDbContext : DbContext
{
public required DbSet<Person> People { get; set; }
// other DbSets
}
public class MyDbContext : DbContext
{
public required DbSet<Person> People { get; set; }
// other DbSets
}
3. Create a migration
dotnet ef migrations add AddedPersonTable
dotnet ef migrations add AddedPersonTable
4. Apply the migration
dotnet ef database update
dotnet ef database update
5. Use it
public class PeopleController : ControllerBase
{
private MyDbContext _ctx;
public SomethingController(MyDbContext ctx) => _ctx = ctx;

[HttpPost]
public Task<IActionResult> AddPerson(string name, DateOnly birthday)
{
var person = new Person {
Name = name,
Birthday = birthday
};
_ctx.People.Add(person);
await _ctx.SaveChanges();
}
}
public class PeopleController : ControllerBase
{
private MyDbContext _ctx;
public SomethingController(MyDbContext ctx) => _ctx = ctx;

[HttpPost]
public Task<IActionResult> AddPerson(string name, DateOnly birthday)
{
var person = new Person {
Name = name,
Birthday = birthday
};
_ctx.People.Add(person);
await _ctx.SaveChanges();
}
}
There's no CLI for creating classes or seeding, though
remmy_clarke_jr
remmy_clarke_jr17mo ago
Could easily create one
Angius
Angius17mo ago
Oh yeah
Vyrania
Vyrania17mo ago
Really? Because it is nice that I could seed the database and everything without having the site up and running.
Angius
Angius17mo ago
Just place your database models and the dbcontext in a separate project And have a console app that references them And use that console app for seeding
Vyrania
Vyrania17mo ago
ah okay alright thank you!
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.