i want to make a relationship between aspnetusers and table uservotes.i did this relationship according to docs but whent i want to add data to uservotes and savechanges the compiler stops in savechanges line.does anyone khow the problem?thank you for any help.
public class UserVote
{
[Key]
public int VoteId { get; set; }
public string ClientId { get; set; }
public int Hpid { get; set; }
public int Hplid { get; set; }
[ForeignKey(nameof(Hpid))]
public TableHp TableHp { get; set; }
[ForeignKey(nameof(Hplid))]
public TableHpl TableHpl { get; set; }
[ForeignKey(nameof(ClientId))]
public ApplicationUser Applicationuser { get; set; }
}
public class ApplicationUser:IdentityUser
{
public virtual List<UserVote> UserVotes { get; set; }
}
public async Task<int> AddvoteForHp(int hpid, string userid)
{
UserVote vote = new UserVote()
{
Hpid = hpid,
ClientId = userid
};
await _context.AddAsync(vote);
await _context.SaveChangesAsync();
var user = await GetPersonByIdAsync(hpid);
user.Like++;
_context.TableHps.Update(user);
await _context.SaveChangesAsync();
return user.Like;
}
I have three tables. Users Notification and Company. I have to made relation one to many which one user can have many notification from company. Notification have to be seen only for users from this company. Example users A company B can see notification only from company B not from the others. How to create query and check user which is actually logged in? Can you help me? I show the code.
[Table("Core.Powiadomienias")]
public class Powiadomienia : Entity
{
public string Tytul { get; set; }
public string Tresc { get; set; }
public long? Firma { get; set; }
public ICollection<User> Users { get; set; }
}
public class User : Entity, IUserIdentity, IAuditable, ILoggable,
IConfidential
{
#region User()
public User()
{
LockoutEnabled = true;
Roles = new List<Role>();
}
#endregion
public Guid PublicId { get; set; }
public DateTime DateCreatedUtc { get; set; }
public DateTime? DateModifiedUtc { get; set; }
public long CreatedBy { get; set; }
public long? ModifiedBy { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public bool IsAdmin { get; set; }
public string RolesGroupsXml { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public string JobPosition { get; set; }
public string HomeCity { get; set; }
public string HomeStreet { get; set; }
public string HomeHouseNo { get; set; }
public string HomeFlatNo { get; set; }
public string HomePostCode { get; set; }
public string HomeCountry { get; set; }
public long? FacePictureId { get; set; }
public virtual File FacePicture { get; set; }
public long? FirmaId { get; set; }
public Powiadomienia Powiadomienia { get; set; }
#region GetList()
public static IEnumerable<TResult> GetList<TResult>(IPager pager, string
tytul , string tresc = null, long? firma = null)
{
using (var context = Context.Read())
{
Slave db = new Slave();
var query = context.Query<Powiadomienia>().AsQueryable();
if (!String.IsNullOrEmpty(tytul))
{
query = query.Where(p => p.Tytul.Contains(tytul));
}
if (!String.IsNullOrEmpty(tresc))
{
query = query.Where(p => p.Tresc.Contains(tytul) &&
db.Firmy.Select(x => x.Nazwa).Equals(p.Firma));
}
if (firma.HasValue)
{
var value = String.Format("<item>{0}</item>", firma);
query = query.Where(p => p.Firma.HasValue);
}
return query
.Pager(pager)
.GetResult<TResult>();
}
}
public class UserService
{
#region GetList()
public static IEnumerable<TResult> GetList<TResult>(IPager pager, string
userName = null, string givenName = null, string surname = null, long? role
null, bool? isAdmin = null, long? firmaid = null)
{
using (var context = Context.Read())
{
var query = context.Query<User>().AsQueryable();
if (!String.IsNullOrEmpty(userName))
{
query = query.Where(p => p.UserName.Contains(userName));
}
if (!String.IsNullOrEmpty(givenName))
{
query = query.Where(p => p.GivenName.Contains(givenName));
}
if (!String.IsNullOrEmpty(surname))
{
query = query.Where(p => p.Surname.Contains(surname));
}
if (firmaid.HasValue)
{
var value = String.Format("<item>{0}</item>", firmaid.Value);
query = query.Where(p => p.FirmaId.HasValue);
}
if (isAdmin.HasValue && isAdmin.Value == true)
{
query = query.Where(p => p.IsAdmin == true);
}
return query
.Pager(pager)
.GetResult<TResult>();
}
}
#endregion
I have a OrderDetails table. I'm trying to get all its contents but its not working. If someone can point out why it's not getting any data that would be very helpful. And yes I have data in OrderDetails table and connection is alright.
OrderDetail.cs
public class OrderDetail
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int odid { get; set; }
public int oid { get; set; }
public virtual Order order { get; set; }
public int pid { get; set; }
public int qty { get; set; }
public int total { get; set; }
public virtual Product Aproduct { get; set; }
}
OrderDetailsController.cs
private static readonly IOrderDetailRepository _orders = new OrderDetailRepository();
// GET api/<controller>
public IEnumerable<OrderDetail> Get()
{
return _orders.GetAll();
}
OrderDetailRepository.cs
private readonly MediaSoftContext _db;
public OrderDetailRepository()
{
_db = new MediaSoftContext();
}
public IEnumerable<OrderDetail> GetAll()
{
return _db.OrderDetails;
}
I am using ASP.NET MVC 4 code first pattern for database layer. I have a many to many relationship between UserProfile and Task. When I try to add a task to the the collection of tasks of a user, it's added but if I try to query it and see if it's there it's not showing up.
My model:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string SirName { get; set; }
public string Position { get; set; }
public string Email { get; set; }
public ICollection<TaskModels> Tasks {get; set; }
public bool? isActive { get; set; }
public UserProfile()
{
Tasks = new HashSet<TaskModels>();
}
}
public class TaskModels
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public ICollection<UserProfile> Employees { get; set; }
public int TimeNeeded { get; set; }
public int TimeWorked { get; set; }
public string Status { get; set; }
public bool isActive { get; set; }
public TaskModels()
{
Employees = new HashSet<UserProfile>();
}
}
public class WorkLogModels
{
public int Id { get; set; }
public UserProfile Author { get; set; }
public DateTime TimeBeganWorking { get; set; }
public int TimeWorkedOn { get; set; }
public TaskModels Task { get; set; }
public string Description { get; set; }
}
public class TimeTrackerDb : DbContext
{
public TimeTrackerDb() : base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<TaskModels> Tasks { get; set; }
public DbSet<WorkLogModels> WorkLogs { get; set; }
}
I try to check if a UserProfile already exists in a Task's Employees list and it's always empty.
[HttpPost]
public ActionResult Create(WorkLogModels worklogmodels)
{
var tasks = db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).SingleOrDefault();
if (tasks == null)
{
return View(worklogmodels);
}
if (ModelState.IsValid)
{
var user = db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
var task = db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).FirstOrDefault();
WorkLogModels log = new WorkLogModels();
log.Description = worklogmodels.Description;
log.TimeBeganWorking = worklogmodels.TimeBeganWorking;
log.TimeWorkedOn = worklogmodels.TimeWorkedOn;
log.Author = user;
log.Task = task;
db.WorkLogs.Add(log);
if (!db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).First().Tasks.Any(x=> x.Name == worklogmodels.Task.Name))
{
db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).FirstOrDefault().Tasks.Add(task);
db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).FirstOrDefault().Employees.Add(user);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(worklogmodels);
}
I've been fighting with this for two days now.
Any help will be greatly appreciated
EDIT:
I am not sure if I made myself clear. In the Crate action for the WorkLog Controller I am trying to put the current user in the current task's collection and vice versa. It works correctly the first time, but then if I do it again it fails to skip the if statement and tries to add it once again and throws an exception : System.Data.SqlClient.SqlException. It's trying to add the same record to the intermediate table.
public ActionResult Index()
{
testEntities6 devicesEntities = new testEntities6();
List<DevicesModel> devicesModel = new List<DevicesModel>();
var device_query = from d in devicesEntities.device
join dt in devicesEntities.devicetype on d.DeviceTypeId equals dt.Id
join l in devicesEntities.location on d.Id equals l.DeviceId
join loc in devicesEntities.locationname on l.LocationNameId equals loc.Id
where l.DeviceId == d.Id
select new {
//devices
d.Id,
d.DeviceTypeId,
d.SerialNumber,
d.FirmwareRev,
d.ProductionDate,
d.ReparationDate,
d.DateOfLastCalibration,
d.DateOfLastCalibrationCheck,
d.CalCertificateFile,
d.Notes,
d.TestReportFile,
d.WarrantyFile,
d.CertificateOfOriginFile,
d.QCPermissionFile,
d.Reserved,
d.ReservedFor,
d.Weight,
d.Price,
d.SoftwareVersion,
//devicetype
dt.Name,
dt.ArticleNumber,
dt.Type,
//location
l.StartDate, //AS LastStartDate,
l.LocationNameId,
//locationname
Loc_name = loc.Name //AS CarrentLocation
};
foreach (var dv in device_query) {
devicesModel.Add(new DevicesModel(
//device
DeviceTypeId = dv.DeviceTypeId,
/*Why I have this error: The name 'DeviceTypeId' does not exist in the current context*/
...
));
}
return View(devicesModel);
}
Model:
public class DevicesModel
{
//device
public int deviceTypeId;
public int id;
public int serialNumber;
public string firmwareRev;
public DateTime productionDate;
public DateTime reparationDate;
public DateTime dateOfLastCalibration;
public DateTime dateOfLastCalibrationCheck;
public int calCertificateFile;
public string notes;
public int testReportFile;
public int warrantyFile;
public int certificateOfOriginFile;
public int qCPermissionFile;
public int BReserved;
public string reservedFor;
public double weight;
public int price;
public string softwareVersion;
//devicetype
public string name;
public string qrticleNumber;
public string type;
//location
public DateTime startDate;
public int locationNameId;
//locationname
public string loc_name;
public DevicesModel(){}
//device
public int DeviceTypeId{get;set;}
public int Id { get; set; }
public int SerialNumber { get; set; }
public string FirmwareRev { get; set; }
public DateTime ProductionDate { get; set; }
public DateTime ReparationDate { get; set; }
public DateTime DateOfLastCalibration { get; set; }
public DateTime DateOfLastCalibrationCheck { get; set; }
public int CalCertificateFile { get; set; }
public string Notes { get; set; }
public int TestReportFile { get; set; }
public int WarrantyFile { get; set; }
public int CertificateOfOriginFile { get; set; }
public int QCPermissionFile { get; set; }
public int bReserved { get; set; }
public string ReservedFor { get; set; }
public double Weight { get; set; }
public int Price { get; set; }
public string SoftwareVersion { get; set; }
//devicetype
public string Name { get; set; }
public string ArticleNumber { get; set; }
public string Type { get; set; }
//location
public DateTime StartDate { get; set; }
public int LocationNameId { get; set; }
//locationname
public string Loc_name { get; set; }
}
Its because you're creating an anonymous object in your linq "Select" clause. I think you want to create an instance of your DevicesModel class, e.g.
...
where l.DeviceId == d.Id
select new DevicesModel {
//devices
Id = d.Id,
...
I think you intend to use curly brackets instead of round brackets.
new DevicesModel
{
//device
DeviceTypeId = dv.DeviceTypeId,
...
}
or are you trying to use named arguments in C#4?