Controller
public ActionResult Index(int? id)
{
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 following error for the line var model = db.Staffs.Where(i => i.Email == userEmail).Include("Histories").Include("CurrentApplications").FirstOrDefault(); but i don't know why I got it.
Error
A specified Include path is not valid. The EntityType
'StaffPortalDBModel.Staff' does not declare a navigation property with
the name 'Histories'.
Staff class
public partial class Staff
{
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 IEnumerable<History> Histories { get; set; }
public virtual IEnumerable<CurrentApplication> CurrentApplications { get; set; }
}
I believe you may need to use ICollection and not IEnumerable when defining Navigation properties. This may be the issue.
I'd also recommend (assuming your version of Entity Framework is high enough that it is supported) to use strongly typed Includes so that if you change your property in Staff.cs you'll get a compile time error.
ie: .Include(s => s.Histories)
Related
Please why am I having this error in the repository
Error 18 The property or indexer 'BPP.CCSP.Admin.Infrastructure.STATES.COUNTRY_ID' cannot be used in this context because it lacks the get accessor
Model
public int STATE_ID { get; set; }
public Nullable<int> COUNTRY_ID { internal get; set; }
public string STATE_NAME { get; set; }
Repository
public class AdminManager : IAdminManager
{
private readonly IRepository<STATES> _statesRepository;
public AdminManager(IRepository<PRB> prbsRepository, IRepository<OPTIONS> optionRepository, IRepository<COUNTRIES> countriesRepository, IRepository<STATES> statesRepository, IRepository<CITIES> citiesRepository)
{
_statesRepository = statesRepository;
}
public SelectList stateList()
{
var countryId = _statesRepository.FindAll().Where(c => c.COUNTRY_ID == 1);
var listStates = countryId.Select(c => new System.Web.Mvc.SelectListItem { Value = c.COUNTRY_ID.ToString(), Text = c.STATE_NAME }).OrderBy(c => c.Text).ToList();
var listCount = new SelectList(listStates, "value", "text");
return listCount;
}
}
Please how do I resolve it.
change
public Nullable<int> COUNTRY_ID { internal get; set; }
to
public Nullable<int> COUNTRY_ID { get; set; }
Note that internal is for assembly scope. Your repository is (i'm guessing) in a different project than where your model is defined. A different project will create a different assembly so then the internal get will not allow the repo to access this property.
I am new to Entity Framework and Asp.NET, and therefore, struggling with creating database relationships within the Entity Framework.
I have two SQLite tables (Ticket and User) and have setup my entity models as follows:
public class Users
{
[ForeignKey("id")]
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
}
public class Tickets
{
public int id { get; set; }
public string summary { get; set; }
public string description { get; set; }
public string c_location { get; set; }
public string c_store_device { get; set; }
public string category { get; set; }
public DateTime? created_at { get; set; }
public DateTime? closed_at { get; set; }
public int priority { get; set; }
public int? assigned_to { get; set; }
public DateTime? due_at { get; set; }
public DateTime? updated_at { get; set; }
public string status { get; set; }
public virtual Users Users { get; set; }
}
I am trying to use Entity Framework 7 to export an IEnumerable<Tickets> that includes the User assigned to each Ticket.
I have tried to create my model relationship in MyDBContext as a single User can have multiple Tickets, and also has a foreign key associated in my Sqlite database (Tickets.assigned_to = User.id):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Users - > many Tickets
modelBuilder.Entity<Users>()
.HasMany(p => p.Tickets)
.WithOne(e => e.Users)
.HasForeignKey(p => p.assigned_to);
}
My result ends up with Ticket data being exported, but against every ticket I see a null value for User:
[{"id":10002,...,"Users":null}]
When I use .Include() within my Repository to include each User like this:
public IEnumerable<Tickets> GetAll()
{
return _db.Tickets.Include(t => t.Users).ToList();
}
It results in the error
HTTP Error 502.3 - Bad Gateway
The specified CGI application encountered an error and the server terminated the process.
What I'm trying to retrieve is data that looks like:
{"Ticket";[{"id":10002,..."status":"closed"}],"Users":[{"id":"1"..."email":"johndoe#someplace.com"}]}
I know it probably has something to do with my relationship model, but I cannot work out what I am doing wrong.
First you should really derive your Users from IdentityUser. It helps when trying to wire up the relationship, but I will give you the answer based on your current models. Your ForeignKey property should be on the child entity. By naming conventions, which is what EF uses by default, your public Users Users works better if you put a public int UsersId. Then essentially what EF will do is from your public Users Users it will go to the Users table. Then it looks for the ForeignKey which is set to Id, so now we are in the Users Table looking at the id property. Then it looks for the naming convention UsersId and if it sees it, it will set that property to the value that it saw from the Users Table Id column.
Try using this
public class Users
{
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
}
public class Tickets
{
public int id { get; set; }
public string summary { get; set; }
public string description { get; set; }
public string c_location { get; set; }
public string c_store_device { get; set; }
public string category { get; set; }
public DateTime? created_at { get; set; }
public DateTime? closed_at { get; set; }
public int priority { get; set; }
public DateTime? due_at { get; set; }
public DateTime? updated_at { get; set; }
public string status { get; set; }
[ForeignKey("Id")]
public int UsersId { get; set; }
public virtual Users Users { get; set; }
}
and for your Fluent API configuring
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Users - > many Tickets
modelBuilder.Entity<Users>()
.HasMany(p => p.Tickets)
.WithOne();
}
Now all that does is create the relationship. In order to view the specific items you want to view, use a ViewModel. So, pull the two lists you want from where you want. Then use logic to separate the list how you want them to display.
public class UsersViewModel()
{
public UsersViewModel(Users user, List<Tickets> tickets)
{
this.first_name = user.first_name;
this.last_name = user.last_name;
this.email = user.email;
this.Tickets = new List<Tickets>();
foreach(var ticket in tickets)
{
if(ticket.UserId == user.Id)
{
this.Tickets.Add(ticket)
}
}
}
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public List<Tickets> Tickets { get; set;}
}
then in your controller make your list
public IActionResult Index()
{
var usersList = _repository.Users.ToList();
var ticketsList = _repository.Tickets.ToList();
var model = new List<UsersViewModel>();
foreach(var user in usersList)
{
var listItem = new UsersViewModel(user, ticketsList);
model.Add(listItem);
}
return View(model);
}
or use a Linq query
public IActionResult Index()
{
var usersList = _repository.Users.ToList();
var model = new List<UsersViewModel>();
foreach(var user in usersList)
{
var ticketsList = from x in _repository.Tickets where x.UserId.Equals(user.Id) select x;
var listItem = new UsersViewModel(user, ticketsList);
model.Add(listItem);
}
return View(model);
}
then at the top of your view you should have
#model IEnumerable<UsersViewModel>
I am getting an error in my mvc application. I am trying to display record from my sql table using entity framework. here is the code which i am trying. But I dnt know why this code giving me error
This is my model
[Table("tbInsertMobile")]
public class tbInsertMobile
{
[Key]
public int MobileID { get; set; }
public string MobileName { get; set; }
public string MobileIMEno { get; set; }
public string mobileprice { get; set; }
public string mobileManufacured { get; set; }
}
my another class in model
public class EmployeeContext:DbContext
{
public DbSet<tbInsertMobile> usermobiles { get; set; }
}
This the code of my contoller
public ActionResult Index(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
tbInsertMobile employee = employeeContext.usermobiles.Single(x => x.MobileID == id);
return View(employee);
}
and now the error which i am getting is this
The 'MobileID' property on 'tbInsertMobile' could not be set to a 'System.Int64' value. You must set this property to a non-null value of type 'System.Int32
Experts Tell me where I am getting this error
Thanks
The answer is there already in the comment.
It's trying to assign a long to an int. Change MobileID to be long. – CodeCaster
I have set up 3 models, code first and the relationships seem to be working but one is causing me a problem.
I have Article, Language and Edition Classes
public class Article
{
public int ID { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
}
public class Language
{
public int ID { get; set; }
public string Name { get; set; }
public string Code { get; set; }
}
public class Edition
{
public int ID { get; set; }
public Article Article { get; set; }
public Language Language { get; set; }
public string Title { get; set; }
public string Details { get; set; }
}
In my bootstrap/DBinitialiser, I can create Objects and populate them fine. The DB is created and the foreign keys for Language and Article are both present on the Edition table and correctly entered.
var engLang = new Language() {Code="en", Name="English Language"};
var altLang = new Language() {Code="xx", Name="Alternative Language"};
db.Languages.Add(engLang);
db.Languages.Add(altLang);
db.SaveChanges();
var testArt = new Article() { Name = "test" };
db.Articles.Add(testArt);
db.SaveChanges();
db.Editions.Add(new Edition(){Article = testArt, Language = engLang, Title="English Content"});
db.Editions.Add(new Edition(){Article = testArt, Language = altLang, Title="Alternative Content"});
db.SaveChanges();
I can now query the Editions and return a list of them, but the Language attribute is always NULL. The Article Attribute works fine.
var query = db.Editions.Where(r => r.Article.ID == Article.ID);
foreach (Edition item in query)
{
// item.Language => NULL
// item.Article => {Object Article}
}
I'm new to .net and Entity-Framework and can't work out why I always get this error.
I can even query by r => r.Language.ID == 1 and still get a NULL attribute on the Edition object.
Make sure you are using EF codefirst in right manner. Here you have some ambiguities. You must determine what relationships actually should exist, in your POCOs. Change classes like bellow:
public class Article
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
}
public class Language
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Code { get; set; }
}
public class Edition
{
[Key]
public int ID { get; set; }
public virtual Article Article { get; set; }
public virtual Language Language { get; set; }
public string Title { get; set; }
public string Details { get; set; }
}
With thanks to AmirHossein Mehrvarzi for helping me write my models more clearly, I believe this error to be caused by the lazy loading of entities while iterating through the result of the query. ref: Entity Framework: There is already an open DataReader associated with this Command.
Without enabling MultipleActiveResultSets I simply added an Include statement to my linq
var query = db.Editions.Where(r => r.Article.ID == Article.ID).Include(r => r.Language);
foreach (Edition item in query)
{
// item.Language => {Object Language}
// item.Article => {Object Article}
}
ASP.net MVC3 Razor EF
When I do this it works:
public ViewResult Index()
{
return View(db.Songs.Include("Artist").ToList());
}
But this doesn't:
public ViewResult Index()
{
return View(db.Artists.Include("Song").ToList());
}
I get this error:
A specified Include path is not valid. The EntityType 'MVCProject.Models.Artist' does not declare a navigation property with the name 'Song'.
Any idea why? if you need more info/code please mention which. but please let me know where something like that can happen, and how it can be solved. it's driving me crazy.
Thanks.
Artists Class:
public class Artist
{
public int ArtistID{ get; set; }
public string Name { get; set; }
public IQueryable<Song> Songs{ get; set; }
}
Replace public IQueryable<Song> Songs{ get; set; } with public virtual ICollection<Song> Songs{ get; set; }
public class Artist
{
public int ArtistID{ get; set; }
public string Name { get; set; }
public virtual ICollection<Song> Songs{ get; set; }
}
Then
return View(db.Artists.Include("Songs").ToList());
You probably have Songs (plural) as navigational property for Artist class. So, return View(db.Artists.Include("Songs").ToList()); should work. If ot - you need to show Model class for Artist