I have two sets of codes. The first one doesn't give me the list of data but the second on does. Please see codes below:
First Code:
Model
public class Student
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
DataConnection
public class DataConnection : DbContext
{
public DataConnection()
: base("DefaultConnection")
{
}
public DbSet<Student> Students { get; set; }
}
Interface
public interface IStudent
{
List<Student> StudentList();
void InsertStudent(Student student);
void UpdateStudent(Student student);
Student GetStudentById(int id);
void DeleteStudent(int id);
}
Concrete
readonly DataConnection _context;
public StudentConcrete()
{
_context = new DataConnection();
}
public List<Student> StudentList()
{
var studentList = (from s in _context.Students select s).ToList();
return studentList;
}
Second Code
Concrete
readonly DataConnection _context;
public StudentConcrete()
{
_context = new DataConnection();
}
public List<Student> StudentList()
{
SqlConnection xxx = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
var cmd = new SqlCommand("GetAllStudents", xxx);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
return (from DataRow row in ds.Tables[0].Rows
select new Student()
{
Age = Convert.ToInt32(row["Age"]),
FirstName = row["FirstName"].ToString(),
Gender = row["Gender"].ToString(),
LastName = row["LastName"].ToString()
}).ToList();
}
else
{
return null;
}
}
I would like to get the data using the first code but I don't know where I get it wrong. My SP is just to get the students.
I suspected that maybe you are retrieving the records from another table somehow. Would you try to add Table attribute for Student entity.
using System.ComponentModel.DataAnnotations.Schema;
[Table("Students")]
public class Student
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
Related
public class Account
{
[Key]
[StringLength(80)]
public string AccountID { get; set; } = string.Empty;
[StringLength(255)]
public string Name { get; set; } = string.Empty;
[ForeignKey(nameof(AccountID))]
public virtual ICollection<Relation> Relations { get; set; }
}
public class Role
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public long RoleID { get; set; } = -1;
[StringLength(80)]
public string RoleName { get; set; } = string.Empty;
}
public class Relation
{
[Key]
[StringLength(80)]
public string AccountID { get; set; } = string.Empty;
[Required]
public long RoleID { get; set; } = 0;
[ForeignKey(nameof(RoleID))]
public virtual Role Role { get; set; }
}
public class AccountsController : ODataController
{
private readonly DS2DbContext _context;
public AccountsController(DS2DbContext context)
{
_context = context;
}
[EnableQuery(PageSize = 20)]
public IQueryable<Account> Get()
{
return _context.Accounts;
}
[EnableQuery]
public SingleResult<Account> Get([FromODataUri] string ID)
{
var result = _context.Accounts.Where(
e => string.Compare(e.AccountID, ID, StringComparison.InvariantCultureIgnoreCase) == 0);
return SingleResult.Create(result);
}
}
The controller is called by a grid which is querying a list of Account records as well as code that reads a single Account record with a given account id.
List query:
https://localhost:44393/DS/Accounts?$count=true&$expand=UserInfo,Relations($expand=Role)&$skip=0&$top=20
Single record query:
https://localhost:44393/DS/Accounts('bt0388')?$expand=UserInfo,Relations($expand=Role)
As long as the SingleResult<Account> Get() method is commented out, the list query ends up in IQueryable<Account> Get() as it should and the query works fine.
As soon as I uncomment SingleResult<Account> Get(), the list query ends up in the SingleResult<Account> Get() and fails.
The single record query never reaches SingleResult<Account> Get(). Omitting the $expand parameter doesn't change anything.
What is going wrong here, and how do I fix it?
I am new to ef core. I am trying to implement many to many .
Here is my DBContext
public class MaxCiSDbContext : DbContext
{
public DbSet<Job> Jobs { get; set; }
public DbSet<Staff> Staffs { get; set; }
public MaxCiSDbContext(DbContextOptions<MaxCiSDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Job>()
.HasMany(t => t.Staffs)
.WithMany(t => t.Jobs);
base.OnModelCreating(modelBuilder);
}
}
and Here is my Staff Class
public class Staff
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
//Navigation
public virtual ICollection<Job> Jobs { get; set; }
}
Here is my Job Class
public class Job
{
[Key]
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string State { get; set; }
public string ClientOrderNumber { get; set; }
public string StartDate { get; set; }
public string DueDate { get; set; }
public string CompletedDate { get; set; }
public string ClientId { get; set; }
public string ManagerId { get; set; }
public string PartnerId { get; set; }
//Navigation
public virtual ICollection <Staff> Staffs { get; set; }
}
I Call an API which returns a XmlDocument, I read that document and update database.
Here is how I deal with xmldocument.
//Fetch Current Jobs and populate to DB
XmlDocument apiresults = JobMethods.GetCurrent();
XmlNodeList nodes = apiresults.DocumentElement.SelectNodes("/Response/Jobs/Job");
foreach (XmlNode node in nodes)
{
Job MaxCiSJob = new Job()
{
Id = node.SelectSingleNode("ID").InnerText,
Name = node.SelectSingleNode("Name").InnerText,
Description = node.SelectSingleNode("Description").InnerText,
State = node.SelectSingleNode("State").InnerText,
ClientOrderNumber = node.SelectSingleNode("ClientOrderNumber").InnerText,
StartDate = node.SelectSingleNode("StartDate").InnerText,
DueDate = node.SelectSingleNode("DueDate") != null ? node.SelectSingleNode("DueDate").InnerText : "",
CompletedDate = node.SelectSingleNode("CompletedDate") != null ? node.SelectSingleNode("CompletedDate").InnerText : "",
ClientId = node.SelectSingleNode("Client/ID").InnerText,
ManagerId = node.SelectSingleNode("Manager/ID") != null ? node.SelectSingleNode("Manager/ID").InnerText : "",
PartnerId = node.SelectSingleNode("Partner") != null ? node.SelectSingleNode("Partner").InnerText : ""
};
XmlNodeList Assigned = node.SelectNodes("Assigned/Staff");
MaxCiSJob.Staffs = new Collection<Staff>();
foreach (XmlNode staffNode in Assigned)
{
var staffId = staffNode.SelectSingleNode("ID").InnerText;
var staff = _db.Staffs.Find(staffId);
if(staff != null)
{
MaxCiSJob.Staffs.Add(staff);
}
}
if (_db.Jobs.Find(MaxCiSJob.Id) == null)
{
//Insert Record
_db.Jobs.Add(MaxCiSJob);
}
else
{
// UPDATE recorde
_db.Jobs.Update(MaxCiSJob);
}
}
_db.SaveChanges();
}
Everything works well when I run the program for the first time(The linking table ,"JobStaff", is empty) but when I run the Program for the second time I get an excetpion:
SqlException: Violation of PRIMARY KEY constraint 'PK_JobStaff'. Cannot insert duplicate key in object 'dbo.JobStaff'. The duplicate key value is (J14995, 557898).
Can someone please help me on how can I resolve this issue.
Running your code EF core wants to add entities anyway. Because your entities are not attached.
Try this code:
//Fetch Current Jobs and populate to DB
XmlDocument apiresults = JobMethods.GetCurrent();
XmlNodeList nodes = apiresults.DocumentElement.SelectNodes("/Response/Jobs/Job");
foreach (XmlNode node in nodes)
{
var id = node.SelectSingleNode("ID").InnerText;
Job MaxCiSJob = _db.Jobs.Find(id);
if (MaxCiSJob == null)
{
MaxCiSJob = new Job() { Id = id };
_db.Jobs.Add(MaxCiSJob);
}
MaxCiSJob.Name = node.SelectSingleNode("Name").InnerText;
MaxCiSJob.Description = node.SelectSingleNode("Description").InnerText;
MaxCiSJob.State = node.SelectSingleNode("State").InnerText;
MaxCiSJob.ClientOrderNumber = node.SelectSingleNode("ClientOrderNumber").InnerText;
MaxCiSJob.StartDate = node.SelectSingleNode("StartDate").InnerText;
MaxCiSJob.DueDate = node.SelectSingleNode("DueDate") != null ? node.SelectSingleNode("DueDate").InnerText : "";
MaxCiSJob.CompletedDate = node.SelectSingleNode("CompletedDate") != null ? node.SelectSingleNode("CompletedDate").InnerText : "";
MaxCiSJob.ClientId = node.SelectSingleNode("Client/ID").InnerText;
MaxCiSJob.ManagerId = node.SelectSingleNode("Manager/ID") != null ? node.SelectSingleNode("Manager/ID").InnerText : "";
MaxCiSJob.PartnerId = node.SelectSingleNode("Partner") != null ? node.SelectSingleNode("Partner").InnerText : "";
XmlNodeList Assigned = node.SelectNodes("Assigned/Staff");
foreach (XmlNode staffNode in Assigned)
{
MaxCiSJob.Staffs.Clear();
var staffId = staffNode.SelectSingleNode("ID").InnerText;
var staff = _db.Staffs.Find(staffId);
if (staff != null)
{
MaxCiSJob.Staffs.Add(staff);
}
}
}
_db.SaveChanges();
And you should change your domains this way in order not to get NullReferenceException:
public class Staff
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
//Navigation
public virtual ICollection<Job> Jobs { get; set; } = new Collection<Job>();
}
public class Job
{
[Key]
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string State { get; set; }
public string ClientOrderNumber { get; set; }
public string StartDate { get; set; }
public string DueDate { get; set; }
public string CompletedDate { get; set; }
public string ClientId { get; set; }
public string ManagerId { get; set; }
public string PartnerId { get; set; }
//Navigation
public virtual ICollection<Staff> Staffs { get; set; } = new Collection<Staff>();
}
I'm new to Entity Framework. At the moment I'm having a problem - when I try to insert a new User object into the database (using method RegisterNewUser), I keep getting an error:
Violation of PRIMARY KEY constraint 'PK__Users__3214EC07705D23AE'. Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is (0).
There are some similar questions here, but none of these answers have helped me.
public void RegisterNewUser(String uName, String uPass, String fName, String lName, String email)
{
User user = new User();
user.Username = uName;
user.Password = uPass;
user.FirstName = fName;
user.LastName = lName;
user.Email = email;
Time time = new Time();
time.Time1 = DateTime.Now;
user.Times.Add(time);
ur.AddUser(user);
}
Time and User objects:
public partial class Time
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int UserId { get; set; }
public System.DateTime Time1 { get; set; }
public virtual User User { get; set; }
}
public partial class User
{
public User()
{
this.Times = new HashSet<Time>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public virtual ICollection<Time> Times { get; set; }
}
Repository file
public class UsersRepository
{
UsersDBContext userDBContext = new UsersDBContext();
public List<User> GetUsers()
{
return userDBContext.Users.Include("Times").ToList();
}
public void AddUser(User user)
{
userDBContext.Users.Add(user);
userDBContext.SaveChanges();
}
}
And context
public partial class UsersDBContext : DbContext
{
public UsersDBContext() : base("name=UsersDBContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Time> Times { get; set; }
public virtual DbSet<User> Users { get; set; }
}
I have no idea how to solve this so any suggestions would be very helpful
set a value of Id field
or
define the Id field as autoincrement
Using code first (EF 6), I created a 1 parent - 2 child relationship. Property is the parent object and Property Address as a child with 1 or 0..1 relationship. PropertyImage is another child with 1 to many relationship. PropertyImage works fine but the PropertyAddress throws error if I try to eager load .
Actual Error -
Multiplicity constraint violated.
The role 'PropertyAddress_Property_Source' of the relationship 'MyAssetTracker.DataLayer.Models.PropertyAddress_Property' has multiplicity 1 or 0..1.
// Test Function
GetProperty()
{
Property property;
using (var repo = new PropertyRepository())
{
property = repo.AllIncluding(a=>a.Images, a=>a.Address).FirstOrDefault(a => a.Id == testpropertyid);
}
}
//Property Repository
public class PropertyRepository : IPropertyRepository
{
public IQueryable<Property> AllIncluding(params Expression<Func<Property, object>>[] includeProperties)
{
IQueryable<Property> query = context.Properties;
foreach (var includeProperty in includeProperties) {
query = query.Include(includeProperty);
}
return query;
}
}
//Property Entity
public class Property : DomainModelAuditBase, IDomainModelState
{
private Address _address;
private ICollection<Asset> _assets;
private ICollection<PropertyImage> _images;
public Property()
{
_address = new Address();
_assets = new List<Asset>();
_images = new List<PropertyImage>();
}
public Guid Id { get; set; }
[StringLength(100), Required]
public string Title { get; set; }
public bool IsPrimary { get; set; }
[StringLength(255)]
public string Description { get; set; }
[NotMapped]
public State State { get; set; }
public Guid AddressId { get; set; }
public Guid UserId { get; set; }
public virtual Address Address
{
get { return _address; }
set { _address = value; }
}
public virtual ICollection<Asset> Assets
{
get { return _assets; }
set { _assets = value; }
}
public virtual User User { get; set; }
public virtual ICollection<PropertyImage> Images
{
get { return _images; }
set { _images = value; }
}
}
//PropertyAddress
public class Address : DomainModelAuditBase, IDomainModelState
{
[Key,ForeignKey("Property")]
public Guid PropertyId { get; set; }
[StringLength(255),Required]
public string AddressLine1 { get; set; }
[StringLength(255)]
public string AddressLine2 { get; set; }
[StringLength(255)]
public string City { get; set; }
[StringLength(255)]
public string StateProvince { get; set; }
[StringLength(100)]
public string PostalCode { get; set; }
[StringLength(100)]
public string Country { get; set; }
[NotMapped]
public State State { get; set; }
public virtual Property Property { get; set; }
}
Remove_address = new Address(); from Property constructor.
You could read about similar problem here
Also are you sure that you need AddressId field in Property class?
I am trying to come up with an edit action. See below for what i have so far.
ViewModel:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GlobalUnitedSC.WebUI.Models
{
public sealed class CreateMensPlayerViewModel
{
//Player profile starts here
[HiddenInput(DisplayValue=false)]
public int MensTeamId { get; set; }
[HiddenInput(DisplayValue = false)]
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime? BirthDate { get; set; }
[Required]
public string Position { get; set; }
public int ShirtNumber { get; set; }
[DataType(DataType.Date)]
public DateTime? Joined { get; set; }
public string Country { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
[DataType(DataType.PhoneNumber)]
public string PhoneNumber { get; set; }
//Player Statistics starts here
public int Games { get; set; }
public int Goals { get; set; }
public int Assists { get; set; }
public int TotalShots { get; set; }
public int ShotsOnGoal { get; set; }
public int FoulsDrawn { get; set; }
public int FoulsCommitted { get; set; }
public int Saves { get; set; }
public int BlueCards { get; set; }
public int YellowCards { get; set; }
public int RedCards { get; set; }
}
}
Create Actions:
[HttpGet]
public ActionResult Create(int mensTeamId)
{
new CreateMensPlayerViewModel {MensTeamId = mensTeamId};
return View();
}
[HttpPost]
public ActionResult Create(CreateMensPlayerViewModel viewModel, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
var mensTeam = _dataSource.MensTeams.Single(t => t.Id == viewModel.MensTeamId);
var mensPlayer = new MensPlayer
{
Name = viewModel.Name,
BirthDate = viewModel.BirthDate,
Position = viewModel.Position,
ShirtNumber = viewModel.ShirtNumber,
Joined = viewModel.Joined,
Country = viewModel.Country,
Description = viewModel.Description,
EmailAddress = viewModel.EmailAddress,
PhoneNumber = viewModel.PhoneNumber,
Games = viewModel.Games,
Goals = viewModel.Goals,
Assists = viewModel.Assists,
TotalShots = viewModel.TotalShots,
ShotsOnGoal = viewModel.ShotsOnGoal,
FoulsDrawn = viewModel.FoulsDrawn,
FoulsCommitted = viewModel.FoulsCommitted,
Saves = viewModel.Saves,
BlueCards = viewModel.BlueCards,
YellowCards = viewModel.YellowCards,
RedCards = viewModel.RedCards
};
mensTeam.MensPlayers.Add(mensPlayer);
_dataSource.Save();
TempData["message"] = string.Format("{0} has been saved", mensPlayer.Name);
return RedirectToAction("detail", "MensTeam", new {id = viewModel.MensTeamId});
}
return View(viewModel);
}
HttpGet Edit Action
[HttpGet]
public ActionResult Edit (int id)
{
var mensPlayer = _dataSource.MensPlayers.FirstOrDefault(p => p.Id == id);
return View(mensPlayer);
}
Now could anyone please help me with the HttpPost Edit action, preferably one based on the model class mentioned above?
I was hoping it has something to do with the line below, if this creates a new player, what could i write to edit that player?
var mensPlayer = new MensPlayer {}
Since it's a post the method is kind of equal to your create-method. You will receive a MensPlayer as a parameter.
Than you check if the Model is valid (validation etc.) and flag the entry as modified and save the changes.
[HttpPost]
public ActionResult Edit(MyModel myModel)
{
if (ModelState.IsValid)
{
DbContext.Entry(myModel).State = EntityState.Modified;
DbContext.SaveChanges();
return RedirectToAction("Index");
}
return View(myModel);
}
DBContext
public class ModelContext : DbContext
{
public DbSet<MyModel> MyModelSet{ get; set; }
}
More info about DBContext.
With help of Slauma in the comments in the repost or extension of this question at:
Repost/Extension
This is what he suggested i do and it works.
Add to IDataSource Interface:
void Update(MensPlayer mensPlayer);
Update Implemented in Db class:
void IDataSource.Update(MensPlayer mensPlayer)
{
Entry(mensPlayer).State = EntityState.Modified;
}
Edit Action:
[HttpPost]
public ActionResult Edit(MensPlayer mensPlayer)
{
if (ModelState.IsValid)
{
//Save Player
_dataSource.Update(mensPlayer);
_dataSource.Save();
TempData["message"] = string.Format("{0} has been saved", mensPlayer.Name);
return RedirectToAction("Detail", "MensPlayer", new {id = mensPlayer.Id});
}
return View(mensPlayer);
}
And Just like that all works fine, although i was under the assumption that i would implement Update to the whole DbSet like i did with Save.