C
C#•2y ago
BroodWar1989

Entity Framework not creating tables

I am using code first workflow. Entity framework was creating tables for my models automatically upon adding migrations. It has stopped doing so. How can I fix this issue?
15 Replies
Angius
Angius•2y ago
Are those tables added to the dbcontext?
BroodWar1989
BroodWar1989OP•2y ago
Let me check real quick I haven't needed to manually add them into dbcontext since my first couple tables it was reading my model changes automatically
Angius
Angius•2y ago
What I mean, is DbSet<TheModel> properties If not, are they referenced in other models? If you have Foo and it references Bar, you only need a DbSet<Foo> and EF will figure out that Bar should also be a table Not the best ideal, it's better to add everything as a dbset, but it does work this way
BroodWar1989
BroodWar1989OP•2y ago
Ah ok I understand. I forgot where dbcontext was because I have been referencing other models in models that are in dbcontext 😦 found it, ok I will add it to dbset thank you @Angius I have another issue now. When trying to reference a model in another model i am getting this error The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Movies_dbo.Genres_GenreId". The conflict occurred in database "aspnet-web_template_001-20230102051540", table "dbo.Genres", column 'Id'.
Angius
Angius•2y ago
Show code
BroodWar1989
BroodWar1989OP•2y ago
Angius
Angius•2y ago
And the genre?
BroodWar1989
BroodWar1989OP•2y ago
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace web_template_001.Models
{
public class Genre
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace web_template_001.Models
{
public class Genre
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
the migration worked and created the proper table but now when using Genre inside Movie as a property I get this error
Angius
Angius•2y ago
The Id in Genre doesn't have the [Key] attribute
BroodWar1989
BroodWar1989OP•2y ago
Ok I will add it but it was working on other classes without adding the
[Key]
[Key]
attribute. I will see if it fixes. How can I rollback migrations to a previous migration and try to fix from there. I am still getting the same error
Angius
Angius•2y ago
dotnet ef migrations remove
BroodWar1989
BroodWar1989OP•2y ago
can i rollback to a specific migration
Angius
Angius•2y ago
Yeah
Angius
Angius•2y ago
EF Core tools reference (.NET CLI) - EF Core
Reference guide for the Entity Framework Core .NET Core CLI tools
BroodWar1989
BroodWar1989OP•2y ago
perfect i will check it out and msg here if i have problems thanks so much
Want results from more Discord servers?
Add your server