EF CodeFirst ,how to add custom model to create table? - ef-code-first

I work on ASP.NET MVC 5.1 and follow this post to create my own UserProfile table by Table Per Type (TPT) method.
But how do i want to add another model by code first?
For example, i want to add independent table Country table and Currency table,
I would create the following classes:
Country.cs
namespace MiaPos.Models
{
public class Country
{
// Primary key
public int CountryID { get; set; }
[Required]
public string Name { get; set; }
}
}
Currency.css
namespace MiaPos.Models
{
public class Currency
{
// Primary key
public int CurrencyID { get; set; }
[Required]
public string Name { get; set; }
}
}
DataContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
namespace MiaPos.Models
{
public class DataContext : DbContext
{
public DbSet<Country> Countries { get; set; }
public DbSet<Currency> Currencies { get; set; }
}
}
I place above of them on the Models folder,
but how can i recognize by CodeFirst Add-Migration command on Nuget Console?
I saw some post say EF will auto generate the migration class if i inherit System.Data.Entity.DbContext class.

Related

EF Core Creates 2 Columns For Navigation

I'm trying to link two tables together but EF Core creates two seperate columns for the same navigation property.
This is the ShoppingCart model. It should have the default ApplicationUsers GUID value as foreign key.
public class ShoppingCart : BaseEntity
{
public Guid BasketGuid { get; set; }
public Guid ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<ShoppingCartItem> ShoppingCartItems { get; set; }
}
But it creates the table like the picture below.
How can I change the model so I can insure that only one navigation property is created correctly?

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.

Cannot migrate AspNetUser entity in Entity Framework Code First Approach in .NET

I am developing an ASP.NET MVC project using Visual Studio 2013. I am using Entity Framework Code First Approach to interact with database. But I am having a problem with migrating data because of built-in identity system in ASP.NET. Everything was fine before I touch to identity system.
These are the steps I have done.
I registered an account from UI using built-in identity system. So AspNetUsers table is created in database.
I created AspNetUser class to my code because I need to work with it.
Then I run migration and update database command. It throws error.
This is my AspNetUser class
public class AspNetUser
{
[Required]
public String Id { get; set; }
[Required]
public String UserName { get; set; }
public String PasswordHash { get; set; }
public String SecurityStamp { get; set; }
[Required]
public String Discriminator { get; set; }
}
This is my db context class
public class AyarDbContext : DbContext
{
public AyarDbContext()
: base("DefaultConnection")
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Region> Regions { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<Item> Items { get; set; }
public DbSet<ItemContactInfo> ItemContacts { get; set; }
public DbSet<Gallery> Galleries { get; set; }
public DbSet<Mail> Mails { get; set; }
public DbSet<AspNetUser> AspNetUsers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
This is the error I got.
There is already an object named 'AspNetUsers' in the database.
How can I migrate AspNetUser class? I registered using UI because I auto create the other tables need for identity system. How can I migrate that class and map with AspNetUsers table that is already existing in database.
As the error explains, that table already exists and is accessible in this way:
var user = context.Users.First(u => u.Id == myId);
If you want to extend the user class and add properties, you can inherit it:
public class MyAppUser : IdentityUser
{
// don't include properties already in IdentityUser
public string MyNewProperty { get; set; }
}
http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/

Using complex user type linked to existing table in the new ASP.NET Identity

I'm trying to implement new ASP.NET Identity in my old project. I have an existing table called tda_Contacts in the database. The following code works fine without table attribute and creates all new identity related tables plus TdaContacts table. But when put existing table name in the table attribute ([Table("tda_Contacts")]), then it does nothing and throws Invalid object name 'dbo.UserSecrets' exeption. Also if I put different name in that attribute it works fine and creates a correct table with exactly the same columns and types as existing tda_Contacts.
What am I doing wrong? How to force it to use my existing table?
public class IdentityUser : User
{
public int ContactID { get; set; }
[ForeignKey("ContactID ")]
public virtual TdaContact TdaContact { get; set; }
}
public class CustomUserContext : IdentityStoreContext
{
public CustomUserContext(DbContext db) : base(db)
{
Users = new UserStore<IdentityUser>(db);
}
}
public class MyDbContext : IdentityDbContext<IdentityUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
public MyDbContext() : base("Name=MyConnectionString")
{
}
public IDbSet<TdaContact> TdaContacts { get; set; }
}
[Table("tda_Contacts")]
public class TdaContact
{
[Key]
public int ContactID { get; set; }
[Required]
[MaxLength(50)]
public string FirstName { get; set; }
[Required]
[MaxLength(50)]
public string LastName { get; set; }
[MaxLength(255)]
public string Email { get; set; }
}
P.S. Just discovered that with precreated IdentityUsers table with correct foreign key to tda_Contacts it works as expected.

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