MVC Invalid object name 'dbo.Staffs' error - sql-server

I got the error Invalid object name 'dbo.Staffs'. but I'm not sure why. I actually deleted and recreated my database with EF because previously I had other errors. But I'm quite sure I recreated it correctly because I've done it in the same way for other programs and it works fine.
.edmx database diagram
Controller
private StaffPortalDBEntities1 db = new StaffPortalDBEntities1();
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["StaffPortalDBConnectionString"].ConnectionString);
[Authorize]
public ActionResult Index()
{
var userEmail = User.Identity.Name;
var model = db.Staffs.Where(i => i.Email == userEmail).Include("Histories").Include("CurrentApplications").FirstOrDefault();
return View(model);
}
I got the error is for the line var model = db.Staffs.Where(i => i.Email == userEmail).Include("Histories").Include("CurrentApplications").FirstOrDefault();
Generated Staff class
public partial class Staff
{
public Staff()
{
this.Histories = new HashSet<History>();
this.CurrentApplications = new HashSet<CurrentApplication>();
}
public int StaffID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Nullable<decimal> AllocatedLeave { get; set; }
public Nullable<int> BalanceLeave { get; set; }
public virtual ICollection<History> Histories { get; set; }
public virtual ICollection<CurrentApplication> CurrentApplications { get; set; }
}

Try this:
var model = db.Staffs.Where(i => i.Email == userEmail).Include(x=>x.Histories).Include(x=>x.CurrentApplications).FirstOrDefault();

Related

DatabaseContext delay to update database

I have an issue when I use Code First EF. When I want to insert an User with its Permissions, the user insert well, but in inserting Permissions just after insert user, I see this exception :
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.UserPermissions_dbo.Users_UserId". The conflict occurred in database "DATABASE", table "dbo.Users", column 'UserId'.
Here my code :
public class User
{
public short UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public ObservableCollection<UserPermission> UserPermissions { get; set; }
}
public class UserPermission
{
public int UserPermissionId { get; set; }
public short UserId { get; set; }
public short PermissionEnum { get; set; }
public bool IsPermitted { get; set; }
}
public class DatabaseContext : DbContext
{
public DatabaseContext()
{
}
public DbSet<User> Users { get; set; }
public DbSet<UserPermission> UserPermissions { get; set; }
}
And final code to insert is :
private void ConfirmButton_Click(object sender, RoutedEventArgs e)
{
var user = new User { Username = "myUsername", Password = "12"};
using (var dbContext = new DatabaseContext())
{
dbContext.Users.AddOrUpdate(user);
dbContext.SaveChanges();
}
SaveUserPermissions(user);
}
private void SaveUserPermissions(User user)
{
var userPermissionsToSave = new ObservableCollection<UserPermission>();
foreach (var permission in ThisUserPermissionData.UserPermissions)
{
var newUserPermission = new UserPermission();
newUserPermission.UserId = PageModel.UserId;
newUserPermission.UserPermissionTypeEnum = 4;
userPermissionsToSave.Add(newUserPermission);
}
using (var dbContext = new DatabaseContext())
{
dbContext.UserPermissions.AddOrUpdate(userPermissionsToSave.ToArray());
dbContext.SaveChanges();
}
}
Note that when I set breakpoint after save user, the code perform correctly. But in normal mode, my code has that exception.
Thanks in advance.

how to display data from both two tables in database in a View in mvc4 razor

Can anybody guide me how to display data from two tables in database in view page of MVC4 using razor?i googled it but i didnt find answer for this
LeadDetail.cs
public partial class LeadDetail
{
public int LeadID { get; set; }
public string LeadName { get; set; }
public virtual logintable logintable { get; set; }
}
EmployeDetail.cs
public partial class EmployeDetail
{
public int EmployeID { get; set; }
public int UserID { get; set; }
public string EmployeeName { get; set; }
public virtual logintable logintable { get; set; }
}
Parentview.cs in viewmodels folder
public class Parentview
{
public List<LeadDetail> LeadDetails { get; set; }
public List<EmployeDetail> EmployeDetails { get; set; }
public ParentsInformationViewModel(List<LeadDetail> _LeadDetails, List<EmployeDetail> _EmployeDetails) //Should i pass all the required parameters that i want to display in view ????
{
LeadDetails = _LeadDetails;
EmployeDetails = _EmployeDetails;
}
Homecontroller.cs
public ActionResult view()
{
List<LeadDetail> LeadObj = new List<LeadDetail> ();
List<EmployeDetail> EmployeObj = new List<EmployeDetail> ();
// get list of parents here
Parentview ParentInfoVMObj = new Parentview();
ParentInfoVMObj.LeadDetails = LeadObj;
ParentInfoVMObj.EmployeDetails = EmployeObj;
return View(ParentInfoVMObj);
}
see below sample
First Table
public class Table1
{
public int Id{ get; set; }
public string Name{ get; set; }
}
Second Table
public class Table2
{
public int Id{ get; set; }
public string Name{ get; set; }
}
ViewModel
public class ViewModelForTwoTables
{
public List<Table1> table1Data { get; set; }
public List<Table2> table2Data { get; set; }
}
see below example
public ActionResult TeamStat()
{
var players = db.Players().ToList();
var seasons = db.Seasons().ToList();
var view = new TeamStat()
{
Players = players,
Seasons = seasons
};
return View(view);
}
in view
#foreach (var player in Model.Players) { ....
#foreach (var player in Model.Seasons) { ....

Master/Detail DataGridViews not populating Details DataGridView

I'm using the following technologies: WinForms, Entity Framework 4.4 (5.0 on .NET 4.0), DBContext
I have (what I think is) a very simple Master/Details form, that actually worked just fine before I upgraded from EF 4.0 to EF 4.4. Now, for some reason, the Details DataGridView simply doesn't populate with any data!
Here's my auto-generated schema code:
public partial class RoadMapping
{
public RoadMapping()
{
this.RoadCharacteristics = new HashSet<RoadCharacteristic>();
}
public int RoadMappingID { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public virtual ICollection<RoadCharacteristic> RoadCharacteristics { get; set; }
}
public partial class RoadCharacteristic
{
public RoadCharacteristic()
{
}
public int RoadCharacteristicID { get; set; }
public int RoadMappingID { get; set; }
public string Value { get; set; }
public string Description { get; set; }
public virtual RoadMapping RoadMapping { get; set; }
}
Here's my code that was working with EF 4.0:
SATContext = new SafetyAssessmentToolEntities();
dataGridViewMappings.DataSource = bindingSourceMappings;
dataGridViewDetails.DataSource = bindingSourceDetails;
bindingSourceMappings.DataSource = SATContext.RoadMappings;
bindingSourceDetails.DataSource = bindingSourceMappings;
bindingSourceDetails.DataMember = "RoadCharacteristics";
Here's the code that isn't working with EF 4.4:
SATContext = new SafetyAssessmentToolEntities();
SATContext.RoadMappings.Load();
SATContext.RoadCharacteristics.Load();
dataGridViewMappings.DataSource = bindingSourceMappings;
dataGridViewDetails.DataSource = bindingSourceDetails;
bindingSourceMappings.DataSource = SATContext.RoadMappings.Local.ToBindingList();
bindingSourceDetails.DataSource = bindingSourceMappings;
bindingSourceDetails.DataMember = "RoadCharacteristics";
Please note that bindingSourceMappings and bindingSourceDetails are declared by the form designer.
I know there are a lot of more advanced and code-intensive ways to make this work, but I can't understand why this very simple way of doing it won't work anymore.
Any suggestions?
public partial class SafetyAssessmentToolEntities : DbContext
{
public SafetyAssessmentToolEntities()
: base("name=SafetyAssessmentToolEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<RoadCharacteristic> RoadCharacteristics { get; set; }
public DbSet<RoadMapping> RoadMappings { get; set; }
}

How to grab a property object from DB

I'm having some doubts, maybe newbie doubts but I just got into ASP.NET MVC 4
Basically I would like to know the correct way of grabbing details of an Object inside a model.
In this case Image inside Contractor.
Model:
public class Contractor {
[Key]
public int ContractorID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Address { get; set; }
public Image Avatar { get; set; }
}
public class Image {
[Key]
public int ImageID { get; set; }
[Required]
public string File_name { get; set; }
[Required]
public byte[] File_data { get; set; }
}
public class DATACRUD : DbContext {
public DbSet<Contractor> Companies { get; set; }
public DbSet<Image> Images { get; set; }
}
Controller:
private DATACRUD db = new DATACRUD();
public ActionResult GetContractorAvatar(int id)
{
Contractor contractor = db.Contractors.Find(id);
if (contractor == null)
{
return HttpNotFound();
}
Image avatar = contractor.Avatar;
Problem 1)
avatar == null, but is not suppose to be because when I created the object Contractor, I added the image sucessfully (I checked in the DB and it is there)
The solution I'm seeing is instead of having Image property in Contractor.cs model, I would just put a string property with the image key.
Problem 2)
Even If could grab the image key like I said in the previous problem, when I pass my mouse in Debug mode over
private DATACRUD db = new DATACRUD ();
db.Images is also empty...
return File(avatar.File_data, "image");
}
Because you haven't defined your Image navigation property as virtual, you will have to eager load the Image when loading a Contractor:
db.Contractors.Include("Avatar").SingleOrDefault(c => c.ContractorID == id);
OR
// using System.Data.Entity;
db.Contractors.Include(c => c.Avatar).SingleOrDefault(c => c.ContractorID == id);

Subsonic 3.0.0.5 Migration Row Update

I want to update a table row and I have a following Code
void updatePrimaryPaymentAndSecondaryPaymentSourceTypes()
{
LookUpDetails lookUpDetail = new LookUpDetails();
var repo = new SimpleRepository("E2Lending", SimpleRepositoryOptions.RunMigrations);
lookUpDetail = repo.Single(80);
lookUpDetail.Col1Value = "My Checking Account";
repo.Update(lookUpDetail);
}
public class LookUpDetails
{
[SubSonicPrimaryKey]
public int LookUpDetailId {get; set;}
public int LookUpGroupId { get; set; }
public string Code { get; set; }
public int SortOrder { get; set; }
public string Col1Value { get; set; }
[SubSonicNullString]
public string Col2Value { get; set; }
[SubSonicNullString]
public string Col3Value { get; set; }
[SubSonicNullString]
public string Col4Value { get; set; }
[SubSonicNullString]
public string Col5Value { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public Boolean IsActive { get; set; }
}
When I execute then repo.Update(lookUpDetail); shows me Null reference Exception.
Can you please tell me How I will be able to update a single record in a table?
Regards
I have the very same problem with very simple model class:
class Person
{
public long ID {get;set;}
public string Name { get; set;}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection) {
Person toUpdate = Repository.All<Person>().Single(p => p.ID == id);
TryUpdateModel(toUpdate, collection.ToValueProvider());
Repository.Update(toUpdate); //throws nullreferenceexception
return RedirectToAction("Index");
}
stack trace:
at SubSonic.Query.Update.GetCommand()
at SubSonic.Query.Update.Execute()
at SubSonic.Repository.SimpleRepository.Update[T](T item)
at MvcApplication1.Controllers.PersonController.Edit(Int32 id, FormCollection collection)
in H:\...\Controllers\PersonController.cs:line 71"
My configuration: SubSonic 3, SQLite, empty database
I ran into this problem as well and I was able to download the latest SubSonic source and the issue was already fixed. Just open the SubSonic.Core project and do a build and replace your project's reference to SubSonic.Core.
Download Latest Source
http://github.com/subsonic/SubSonic-3.0
Boom - Repository Update works again!

Resources