Reputation: 263
My insert in two tables is a success but I am getting error on Index action to display the data.
Model and View Models.
View Models
public class VMUsers
{
public int Id { get; set; }
public string FullName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
}
Models
[Table("tblUsers")]
public class Users
{
[Key]
public int Id { get; set; }
public string FullName { get; set; }
public string LastName { get; set; }
}
[Table("tblUserDetails")]
public class UserDetails
{
[Key]
public int Id { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public int UserID { get; set; }
}
DBSet
public System.Data.Entity.DbSet<MVCLearning.Models.VMUsers> Combination { get; set; }
Index Action
public ActionResult Index()
{
return View(db.Combination.ToList());
}
Getting exception
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while executing the command definition. See the inner exception for details.
Cant understand what is this inner excepton.
It breaks so the debug part to see the error also breaks it doesn't goes to the View for debugging.
Upvotes: 0
Views: 466
Reputation: 39376
One thing you should do is create navigation properties between your entities, but first I think you are trying to create an one to one relationship between User
and UserDetail
. If that is the case, the PK of the dependent entity (in this case UserDetail
) also should be FK of your relationship. Your model would be this way:
[Table("tblUsers")]
public class Users
{
[Key]
public int Id { get; set; }
public string FullName { get; set; }
public string LastName { get; set; }
public virtual UserDetail Detail { get; set; }
}
[Table("tblUserDetails")]
public class UserDetails
{
[Key,ForeignKey("User")]
public int UserId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public virtual User User { get; set; }
}
Now the DBSet<TEntity>
properties in your context must be defined using your entity types:
public DbSet<MVCLearning.Models.User> Users { get; set; }
public DbSet<MVCLearning.Models.UserDetail> UserDetails { get; set; }
Now in your controller you can declare a query like this projecting the result in your VM class:
public ActionResult Index()
{
return View(db.Users.Select(u=>new VMUsers{ Id=u.Id,
FullName=u.FullName,
LastName=u.LastName,
Address2=u.Detail.Address1,
Address1=u.Detail.Address2}));
}
Upvotes: 2