add-migration not generating anything - asp.net

So I've tried running "add-migration AddBooking -verbose"
To this class:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace HostelBookingSystem.Models
{
public class Booking
{
[Key]
public Int32 BookingId { get; set; }
public Int32 Duration { get; set; }
public Double Price { get; set; }
public BookingStatus Status { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual Bunk Bunk { get; set; }
public virtual Room RoomPreference { get; set; }
}
}
However I'm receiving completely empty Up() and Down() methods.
The same thing happens when I remove the 3 public virtual attributes as well.
Can any explain why this is?

1) The DBContext class needs to be set up
2) Include the property for the above class in the DBContext
public DbSet<Booking> Books { get; set; }

The reason this didn't generate anything was because I didn't have a DbContext set up for the class I wished to generate a table for.

Related

Introducing FOREIGN KEY constraint on table may cause cycles or multiple cascade paths even after removing the affected field completely

I'm quite new to .net and entity framework (this is my first project) and I'm getting the following error when trying to update the database:
*Introducing FOREIGN KEY constraint 'FK_Rating_User_UserId' on table 'Rating' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.*
I tried doing what it says (at least I think so) by adding the following to my dbContext class:
protected override void OnModelCreating(ModelBuilder modelbuilder)
{
modelbuilder.Entity<Rating>().HasOne(u => u.User).WithMany().OnDelete(DeleteBehavior.Restrict);
modelbuilder.Entity<Rating>().HasOne(g => g.Game).WithMany().OnDelete(DeleteBehavior.Restrict);
}
Not sure have I formulated that method correctly but it did not help (I tried with different DeleteBehavior like SetNull and NoAction)
The thing that really got me confused is that the issue appears even after removing all fields related to other tables from Rating class or even all references between all classes.
My Rating class:
public class Rating
{
public long RatingId { get; set; }
//[Rating]
public virtual Game Game { get; set; } // issue appears even after removing this and User line
//[Rating]
public int Score { get; set; }
public string CommentTitle { get; set; }
public string CommentDescription { get; set; }
//[Rating]
public virtual User User { get; set; }// issue appears even after removing this and Game line
}
User class:
public class User
{
public long UserId { get; set; }
//[Required]
public bool IsModerator { get; set; }
//[Required]
public string Username { get; set; }
//[Required]
public string Email { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
//[Required]
public string Password { get; set; }
//[Required]
public string Salt { get; set; }
public string Description { get; set; }
}
Game class:
public class Game
{
public long GameId { get; set; }
//[Required]
public virtual User User { get; set; }
//[Required]
public string Title { get; set; }
public string Description { get; set; }
//[Required]
public string PricingType { get; set; }
public float MinDonation { get; set; }
public float MaxDonation { get; set; }
//[Required]
public string FileLocation { get; set; }
public float AverageRaiting { get; set; }
public int DownloadCount { get; set; }
}
GameImage class (probably unrelated to the issue just wanted to give a full context)
public class GameImage
{
public long GameImageId { get; set; }
//[Required]
public virtual Game Game { get; set; }
//[Required]
public string Location { get; set; }
//[Required]
public bool IsThumbnail { get; set; }
}
dbContext class:
public class dbContext : DbContext
{
public dbContext(DbContextOptions<dbContext> options) : base(options)
{
}
public DbSet<User> User { get; set; }
public DbSet<Rating> Rating { get; set; }
public DbSet<GameImage> GameImage { get; set; }
public DbSet<Game> Game { get; set; }
}
The issue only appeared after I tried to update the database. The first few migrations and updates were ok, however, then I tried adding [Required] annotation (you can see them commented in the above code) as I noticed that most of the fields were created as nullable in my database - after that the issue starting to occur even after removing the annotations.
In case that matters, I'm using Visual Studio 2019 and SQL Server Express
Does anyone have any idea what may be the cause of this?
Edit:
Image of of my database schema diagram from SSMS
As you can see in the database schema it's visible that there are indeed cycles in the database, however, I cannot get rid of them as Entity Framework's command "Update-Database" does not update the DB and just throws the error mentioned above.
Based on my test, you can try the following steps to solve the problem.
First, please change your dbcontext class into the following code.
public class dbContext : DbContext
{
public dbContext() : base("name=MyContext") { }
public DbSet<User> User { get; set; }
public DbSet<Rating> Rating { get; set; }
public DbSet<GameImage> GameImage { get; set; }
public DbSet<Game> Game { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
Second, please delete all the tables the database.
Third, please try the following command in your package console.
PM> Update-Database -Force
Finally, you can see the new tables in the databse.

Creating navigation code-first results in the error: does not declare a navigation property with the name

query.Include("Store_Location").Load();
throws:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: A specified Include path is not valid. The EntityType 'Model.Order' does not declare a navigation property with the name 'Store_Location'.
I used the following code in order to create the navigation code-first:
public partial class Order
{
public Nullable<int> Store_Location_ID { get; set; }
public virtual Store_Location Store_Location { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
public partial class Store_Location
{
public int ID { get; set; }
public virtual ICollection<Order> Orders { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
https://learn.microsoft.com/en-us/ef/ef6/fundamentals/relationships
Do I need to use the designer? Is there anything I need to do in order for the navigation to be created?
If you create your database with code first approach, then your entities should not be partial classes. Define them like this:
public class Order
{
public int? StoreLocationId { get; set; }
public virtual StoreLocation StoreLocation { get; set; }
}
public class StoreLocation
{
public int Id { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
Then you should create a DbContext class:
public class StoreDbContext : DbContext
{
public StoreDbContext(DbContextOptions<StoreDbContext> options) : base(options)
{
}
public virtual DbSet<StoreLocation> StoreLocations { get; set; }
public virtual DbSet<Order> Orders { get; set; }
}
After creating a context you can use the ef commands to create your database. You can read more about ef core here: https://learn.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli
If you define your classes like I did above, you can include your navigation properties strongly typed like this:
query.Include(order => order.StoreLocation);

MVC ASP.net definition GetEnumerator error

So i get the error message in the title and i dont understand why.
Heres how i reference the model in the view
#model IEnumerable<Lowflix.Models.LendingIndexModel>
The errors coming up in this foreach
#foreach (var item in Model)
Really cant explain to myself how this i get this error since i even declared IEnumerable. It contains multiple objects.
This is the error message:
foreach statemetn cannot operate on variables
of type "Models" because "Models" does not
contain a public instance of GetEnumerator
-
model:
using Lowflix.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Lowflix.Models
{
public class LendingIndexModel
{
public LendingIndexModel()
{
}
public Guid LendingId { get; set; }
public Guid CustomerId { get; set; }
public Guid CopyId { get; set; }
public String Title { get; set; }
public DateTime StartDate { get; set; }
public DateTime? ReturnDate { get; set; }
public virtual Movie Movie { get; set; }
public virtual Customer Customer { get; set; }
public virtual Copy Copy { get; set; }
}
debugging model:
model type:
+ Model {System.Linq.Enumerable.WhereSelectListIterator
<Lowflix.Core.Entities.Lending,
Lowflix.Models.LendingIndexModel>} System.Collections.Generic.IEnumerable
<Lowflix.Models.LendingIndexModel>
{System.Linq.Enumerable.WhereSelectListIterator
<Lowflix.Core.Entities.Lending,
Lowflix.Models.LendingIndexModel>}
Please try with below code.
#model List<Lowflix.Models.LendingIndexModel>
In the View page change IEnumerable to List.

AspNet EF6 - Entity type has no key defined

So I changed up my databases and remade them. I followed the EF6 tutorial but encountered this error when trying to create a controller with views. I did some research on the error and people said to add data annotations and I tried [Key] but I keep getting the same error. Not sure if i've forgotten anything? Thanks!
"There was an error running the selected code generator: 'Unable to retrieve metadata for 'LinkDB.Models.Identifier.' Unable to determine the principal end of an association between the type 'LinkDB.Models.Identifier' and 'LinkDB.Models.Identity'. The principal end of this association must be explicity configured using either the relationship fluent API or data annotation.'
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace LinksDB.Models
{
public class Identity
{
[Key]
public int ID { get; set; }
public int IdentifierID { get; set; }
public string contact { get; set; }
public string contactname { get; set; }
public string price { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual Identifier Identifiers { get; set; }
public virtual Metric Metrics { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace LinksDB.Models
{
public class Identifier
{
[Key]
public int ID { get; set; }
public string domain { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual Identity Identitys { get; set; }
public virtual Metric Metrics { get; set; }
}
}
using LinksDB.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace LinksDB.DAL
{
public class LinkData : DbContext
{
public LinkData() : base("LinkData")
{
}
public DbSet<Identifier> Identifiers { get; set; }
public DbSet<Identity> Identitys { get; set; }
public DbSet<Link> Links { get; set; }
public DbSet<Metric> Metrics { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
OK, if you want a 1:1 relationship between Identity and Identifier those models should look like below where the child (Indentifier) uses the IdentityId as both it's PK and FK. You can also do this with fluent code. Start with this and then add in your Metric and Links relationships.
public class Identity
{
[Key]
public int ID { get; set; }
public string contact { get; set; }
public string contactname { get; set; }
public string price { get; set; }
public virtual Identifier Identifier { get; set; }
}
public class Identifier
{
[Key, ForeignKey("Identity")]
public int IdentityID { get; set; }
public string domain { get; set; }
public virtual Identity Identity { get; set; }
}
Example here

Scaffolding with Entity Framework in ASP.NET MVC 4

I'm following along with "Professional ASP.NET MVC 4" and trying to generate a controller from a model using Entity Framework. My Model looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcMusicStore.Models
{
public class MusicStoreModels
{
public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
public class Artist
{
public virtual int ArtistId { get; set; }
public virtual string Name { get; set; }
}
public class Genre
{
public virtual int GenreId { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual List<Album> Albums { get; set; }
}
}
}
When I right click my Controllers folder and choose Add > Controller I select "MVC controller with read/write action and views, using Entity Framework" as my template and "Album (MvcMusicStore.Models)" as my Model class. The book tells me to select "new data context..." and name it "MvcMusicStore.Models.MusicStoreDBContext".
Everything looks OK and I have saved and built my solution prior to performing the above actions. However, I get an error message saying
There was an error generating 'MvcMusicStore.Models.MusicStoreDBContext'.
Try rebuilding your project.'
I'm at a bit of a loss. Can anyone help?
The symptoms sound a lot like this issue:
http://www.rhysgodfrey.co.uk/archive/2011/04/20/mvc3-tools-update-and-entity-framework-4-1-error.aspx
I would suggest uninstalling all versions of Entity Framework, re-installing the latest version through NuGet, and regenerating your EF context from scratch.
I not very up on C# (i think it is C# code - but dont quote me on that).....
Well after pasting your code in a new project i notice the line that says
Using System.Data.Entity;
Is flagged as an error,
And some further research shows that a refrence is POSSIBLY missing in inyour config.sys file...
Re: http://forums.asp.net/t/1381740.aspx/1

Resources