How to Update model and database with code first approach in Asp.net MVC - asp.net

I'm new to mvc. I've creted an MVC app, in which i have used code first approach. Right now i have two tables Deal and Comment. Now i want to add a new table Category in the database and new column categoryId in Deal table.
How i can update database and model?
I'm using Sql Server 2008 R2 for Database.
I've following structure of class:
namespace FBWebApp.Models
{
public class Deal
{
public int ID { get; set; } // ID
public string Title { get; set; } // Titolo del deal
public string Description { get; set; } // Descrizione dell'annuncio
public string FacebookUID { get; set; } // UID facebook dell'utente
public string Visibility { get; set; } // Visibility
public string Category { get; set; }
public int Option1 { get; set; }
public int Option2 { get; set; }
public int Option3 { get; set; }
public int Option4 { get; set; }
public string PhotoURL { get; set; } // URL of the facebook photo profile
public string Name { get; set; } // Name of the user
public string ProfileUrl { get; set; } // URL of the facebook profile
public string Photo1 { get; set; } // URL of the Photo1 (local )
public string Photo2 { get; set; }
public string Photo3 { get; set; }
public string Photo4 { get; set; }
public string Photo5 { get; set; }
}
public class Comment
{
[Key]
public int CommentId { get; set; }
public string CommentText { get; set; }
public int ID { get; set; }
[ForeignKey("ID")]
public Deal DelNav { get; set; }
}
public class DealDBContext : DbContext
{
public DealDBContext() : base("DealDBContext") { }
public DbSet<Deal> Deals { get; set; }
public DbSet<Comment> Comments { get; set; }
}
}

Try using 'update-database -force -verbose' in the Package Manager Console.
If it doesn't work, modify the migration but typing 'add-migration somename' and it will apear in the Migrations folder.
If you are new to MVC and EF, definitely check out this tutorial. It explains all about that and everything else you need to know:
http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m1-intro&mode=live&clip=0&course=mvc4-building

first add your model :
public class Category
{
public int ID { get; set; }
public int cateName { get; set; }
}
in Deal class :
public class Deal
{
//..
[ForeignKey("CatId")]
public virtual Category Category { get; set; }
}
after Enable Migration you should use this command in console manager to update your database :
update-database

Related

How can I set up two navigation properties of the same type in Entity Framework without use Fluent API

i'm trying create DB using codefirst. i want to create two ForeingKey from same table. But when i set up two navigation properties of the same type, get error like :
The foreign key name 'FollowedUser' was not found on the dependent type Models.UserUserWatchListItem'. The Name value should be a comma separated list of foreign key property names.
public class UserUserWatchListItem
{
public int Id { get; set; }
[Key,ForeignKey("FollowedUser")]
public virtual User FollowedUser { get; set; }
public int FollowedUserId { get; set; }
[Key,ForeignKey("FolloweeUser")]
public int FolloweeUserId { get; set; }
public virtual User FolloweeUser { get; set; }
}
Use this :
public class UserUserWatchListItem
{
public int Id { get; set; }
public int FollowedUserId { get; set; }
public int FolloweeUserId { get; set; }
[ForeignKey("FollowedUser")]
[InverseProperty("FollowedUsers")]
public virtual User FollowedUser { get; set; }
[ForeignKey("FolloweeUser")]
[InverseProperty("FolloweeUsers")]
public virtual User FolloweeUser { get; set; }
}
public class User
{
...
[InverseProperty("FollowedUser")]
public virtual ICollection<UserUserWatchListItem> FollowedUsers { get; set; }
[InverseProperty("FolloweeUser")]
public virtual ICollection<UserUserWatchListItem> FolloweeUsers { get; set; }
}

Save Relation between User and Entity in ASP.NET MVC4

I have an Exercise entity defined in my ASP.NET MVC4 Web Application.
I'm using the Form Authentication with the default AccountModels.cs class.
I have class which looks like
public class Exercise
{
private DateTime _DateCreated = DateTime.Now;
private UserProfile _Teacher;
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public DateTime Date
{
get { return _DateCreated; }
set { _DateCreated = value; }
}
public UserProfile Author
{
get { return _Teacher; }
set { _Teacher = value; }
}
}
Am I using the UserProfile correctly to link between an Exercise and a logged in user?
How can I get the current UserProfile in my controller?
Change it like this:
public class Exercise
{
public Exercise()
{
this.Date = DateTime.Now;
this.Author = User.Identity.Name; //Write this line if you want to set
//the currently logged in user as the Author
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public virtual DateTime Date { get; set; }
public virtual UserProfile Author { get; set; }
}

Entity framework 5: net40

I'm developing a web application with ASP.NET 4.0.
I have a database SQL Server 2005 and I'm using Entity Framework 5 connecting to it.
public class ArchivioClienti : DbContext
{
public ArchivioClienti()
: base("ICAMConnection")
{
}
public DbSet<ClientiProspect> clienti { get; set; }
}
[Table("pvw_clienti_prospect")]
public class ClientiProspect
{
[Key]
public string tipologia { get; set; }
public string cod_ppro { get; set; }
public string rag_soc { get; set; }
public string indirizzo { get; set; }
public string cap { get; set; }
public string citta { get; set; }
public string prov { get; set; }
public string nazione { get; set; }
public string telefono { get; set; }
public string fax { get; set; }
public string part_iva { get; set; }
public string cod_fisc { get; set; }
public string note { get; set; }
public string e_mail { get; set; }
public string cod_ppro_anag { get; set; }
public string cod_vage { get; set; }
public string cod_visp { get; set; }
public string fonte { get; set; }
public string cod_vzon { get; set; }
public decimal perc_provv { get; set; }
public string flag_stato { get; set; }
public string cod_anag { get; set; }
public string gg_chiusura { get; set; }
public DateTime? data_ins { get; set; }
public string cod_canale { get; set; }
}
I'm trying to get data from a table. This isn't a really table but only a view.
When I load a query with LINQ,
var result = from u in dbClienti.clienti
select u;
return result.ToList()
I receive the correct number of results (the same that i receive with the same query in SQL Server Management studio), but with wrong fields: the first one is replicated several times, the second one the same, etc.
Why is it working in this way? Are there any problems on Entity Frameworks with database's views?
I assume your view is correctly configured and returning the correct results when executed outside of Entity Framework?
There's no problem with using a view instead of a table in Entity Framework. I would run SQL Profiler and see what E.F is doing when executing the query.

Entity Framework WebApi Circular dependency serialization error

I think, I've read everything about this error and I tried everything. Here are my models:
Main:
public class Trip
{
public int TripId { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string Country { get; set; }
public float BasicPrice { get; set; }
public virtual ICollection<ApartmentType> ApartmentType { get; set; }
public virtual ICollection<TransportMethod> TransportMethod { get; set; }
public virtual ICollection<FeedingType> FeedingType { get; set; }
}
ApartmentType:
public class TransportMethod
{
public int TransportMethodId { get; set; }
public int TripId { get; set; }
public string Name { get; set; }
public float Price { get; set; }
}
FeedingType:
public class FeedingType
{
public int FeedingTypeId { get; set; }
public int TripId { get; set; }
public string Description { get; set; }
public float Price { get; set; }
}
TransportType:
public class TransportMethod
{
public int TransportMethodId { get; set; }
public int TripId { get; set; }
public string Name { get; set; }
public float Price { get; set; }
}
When serializng the Trip entity I get a circular dependency error. Things i tried:
Disable lazy loading in DbContext.
Adding
json.SerializerSettings.PreserveReferencesHandling=Newtonsoft.Json.PreserveReferencesHandling.All; to GLobal.asax
Adding a decorator [IgnoreDataMember] to TripId in every child entity.
Mapping this entity to a ViewModel which doesn't contain the ICollection members. - This worked ok, but at some point I will want to get those lists to the client.
I really don't know what's going on. What am I missing? I really can't spot any circular dependency.
Have you tried adding the [JsonIgnore] attribute to the TripId to the children entities?
http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonIgnoreAttribute.htm
or setting
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

Model collections of the same class held by several other classes

How do I model the following using Castle ActiveRecord?
I have two classes, Customer and Task.
I would like to reuse a third class, Note, stored in a Collection in each of the Customer and Task classes.
public class Note
{
public int ID { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
public class Customer
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
public class Task
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
I would then like to be able to pass the Notes collection to a Gridview, Listview or Repeater in the relevant ASP.Net page for the Customer or Task classes.
I think what you need is to implement a type hierarchy. You can read about it here.
We settled on the following pattern:
[ActiveRecord]
public class Note
{
[PrimaryKey]
public int ID { get; set; }
[Property]
public string Subject { get; set; }
[Property]
public string Body { get; set; }
[BelongsTo]
public Customer Customer { get; set; }
[BelongsTo]
public Customer Task{ get; set; }
}
[ActiveRecord]
public class Customer
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}
[ActiveRecord]
public class Task
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}

Resources