C
C#2y 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
Angius2y 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
Could easily create one
Angius
Angius2y ago
Oh yeah
Vyrania
VyraniaOP2y ago
Really? Because it is nice that I could seed the database and everything without having the site up and running.
Angius
Angius2y 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
VyraniaOP2y ago
ah okay alright thank you!
Accord
Accord2y 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.
Want results from more Discord servers?
Add your server