MVC one to many user companies and notifiaction - asp.net

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

Related

List of items relate to two tables one contain foreign key other the primary key and check if item contain primary key is not in the database insert

I have task to get list of items which contain properties related to two tables(Item, PurchaseItemOrder), This list contain the Code property related to Item class this property is not the primary key for business reasons. So I have to search in the database by this Code and if this Item does not exist in the database insert it, And finally return the Id of the Item which is the primary key and get this key as foreign key in another table PurchaseItemOrder, I did some code, and I see this question Check if List of Items exist in database and if not Add it to database, but seems not exactly what I want can I do better?
Here May Code look like:
public class Item :Entity<int> , IFullAudited<User>
{
public string Name_en { get; set; }
public string Name_ar { get; set; }
public string Code { get; set; }
public string Description_en { get; set; }
public string Description_ar { get; set; }
public User CreatorUser { get; set; }
public User LastModifierUser { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public User DeleterUser { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
}
public class PurchaseOrderItem : Entity<int>, IFullAudited<User>
{
public int POId { get; set; }
public int Qty { get; set; }
public int ItemId { get; set; }
public virtual Item Item { get; set; }
public User CreatorUser { get; set; }
public User LastModifierUser { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public User DeleterUser { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
public PurchaseOrder PurchaseOrder { get; set; }
}
public class PurchaseOrderItemDto : EntityDto<int>
{
public string PONumber { get; set; }
public List<ItemDto> Items { get; set; }
}
public class ItemDto :EntityDto<int>
{
public string Name_en { get; set; }
public string Name_ar { get; set; }
public string Code { get; set; }
public string Description_en { get; set; }
public string Description_ar { get; set; }
public int Qty { get; set; }
}
private int CheckPO(PurchaseOrderItemDto dto)
{
var poExist = _purchaseOrderRepository.FirstOrDefault(po => po.PONumber == dto.PONumber);
int id;
if (poExist == null)
{
id = _purchaseOrderRepository.InsertAndGetId(new PurchaseOrder
{
PONumber = dto.PONumber,
StatusId = 1
});
}
else
{
id = poExist.Id;
}
return id;
}
private int CheckItem(ItemDto itemDto)
{
var itemExist = _itemRepository.FirstOrDefault(it => it.Code == itemDto.Code);
int id;
if (itemExist == null)
{
id = _itemRepository.InsertAndGetId(new Item
{
Name_en = itemDto.Name_en,
Name_ar = itemDto.Name_en,
Code = itemDto.Code,
Description_en = itemDto.Description_en,
Description_ar = itemDto.Description_ar
});
}
else
{
id = itemExist.Id;
}
return id;
}
public void UploadPurchaseOrderItems(PurchaseOrderItemDto dto)
{
var poId = CheckPO(dto);
foreach (var poItem in dto.Items)
{
int itemId = CheckItem(poItem);
_repository.Insert(new PurchaseOrderItem
{
POId = poId,
Qty = poItem.Qty,
ItemId = itemId
});
}
}

How to modify database having foreign key in asp.net?

I have two tables: SurveyOption and SurveyQuestion, in my DbModel.
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}
public class SurveyQuestions
{
[Key]
public Guid SurveyQuestionsId { get; set; }
public Guid? SurveyMasterId { get; set; }
public int? Sequence { get; set; }
[MaxLength(1)]
public string QuestionType { get; set; }
[MaxLength(500)]
public string QuestionText { get; set; }
public bool? Required { get; set; }
public string ExplanationLink { get; set; }
}
SurveyQuestionId is the foreign key in SurveyOption. While making an update query I repeatedly get an error The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SurveyOptions_SurveyQuestions". The conflict occurred in database "MCNITemp", table "dbo.SurveyQuestions", column 'SurveyQuestionsId'.
My ViewModel of SurveyQuestion consist of OptionList. In which each SurveyQuestion holds its own optionList of type List<SurveyOption> and questionList is of type List<SurveyQuestion>
My modify code is the following:
foreach (var question in questionList)
{
var options = question.OptionsList;
foreach (var option in options)
{
var optionData = _mcniDbContext.SurveyOptions.Where(e => e.SurveyOptionId == option.SurveyOptionId).FirstOrDefault();
if (optionData == null)
{
_mcniDbContext.SurveyOptions.Add(new SurveyOptions()
{
OptionValue = option.OptionValue,
Description = option.Description,
Sequence = option.Sequence,
SurveyOptionId = option.SurveyOptionId,
SurveyQuestionId = option.SurveyQuestionId
});
}
else
{
optionData.SurveyOptionId = option.SurveyOptionId;
optionData.SurveyQuestionId = option.SurveyQuestionId;
optionData.Sequence = option.Sequence;
optionData.OptionValue = option.OptionValue;
optionData.Description = option.Description;
_mcniDbContext.Entry(optionData).State = EntityState.Modified;
}
_mcniDbContext.SaveChanges();
}
var questionData = _mcniDbContext.SurveyQuestions.Where(e => e.SurveyQuestionsId == question.SurveyQuestionsId).FirstOrDefault();
questionData.SurveyQuestionsId = question.SurveyQuestionsId;
questionData.SurveyMasterId = surveyMasterId;
questionData.QuestionText = question.QuestionText;
questionData.QuestionType = question.QuestionType;
questionData.Required = question.Required;
_mcniDbContext.Entry(questionData).State = EntityState.Modified;
_mcniDbContext.SaveChanges();
}
In your model you have let EF know how relationships are working. Assuming you have not used Fluent Api for desribing same, your code can be like below (code has not been test):
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
[ForeignKey("SurveyQuestionId")]
public SurveyQuestion SurveyQuestion {get;set;}
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}

How to save data in many to many relation without duplicate in my Card table [Entity Framework]

I have a problem. I cannot save cards without duplicates.
I have 3 tables a Deck, Card table and a CardDeck table which is the junction table.
The goal is to store a deck in the database without the cards being duplicated.
Table Card
namespace MTG_Deck.Models
{
public class Card
{
[Key]
public int CardId { get; set; }
public string Name { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public string SetName { get; set; }
public string Artist { get; set; }
public string ManaCost { get; set; }
public string Rarity { get; set; }
public string ImageUrl { get; set; }
public string Toughness { get; set; }
public string Power { get; set; }
public string id { get; set; }
public virtual ICollection<DeckCard> Decks { get; set; }
}
}
Table Deck
namespace MTG_Deck.Models
{
public class Deck
{
[Key]
public int DeckId { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime CreateAt { get; set; }
public User User { get; set; }
public virtual ICollection<DeckCard> Cards { get; set; }
}
}
Table CardDeck
namespace MTG_Deck.Models
{
public class DeckCard
{
public int DeckID { get; set; }
public int CardID { get; set; }
public Deck Deck { get; set; }
public Card Card { get; set; }
}
}
CardDeckRequest contains the content of the request.
namespace MTG_Deck.Models
{
public class CardDeckRequest
{
[Required]
public int UserID { get; set; }
[Required]
public string Token { get; set; }
[Required]
public Deck Deck { get; set; }
[Required]
[MinLength(5, ErrorMessage = "The deck must contain 60 cards.")]
public List<Card> Cards { get; set; }
}
}
Controller
[HttpPost]
public IActionResult Add([FromBody] CardDeckRequest request)
{
User user = _context.User.Where(u => u.Token == request.Token).FirstOrDefault<User>();
if (user == null) {
var error = new string[] {"You have to be connected to create a deck!"};
BadRequest(new { errors = new { success = error } });
}
List<DeckCard> deckList = new List<DeckCard>();
if (ModelState.IsValid) {
request.Deck.User = user;
foreach (var item in request.Cards)
{
Card card = _context.Card.FirstOrDefault(c => c.Name == item.Name);
if (card == null) {
card = item;
Console.WriteLine("coucou");
}
DeckCard deckCard = new DeckCard {
Card = card,
Deck = request.Deck
};
deckList.Add(deckCard);
}
_context.DeckCard.AddRange(deckList);
_context.SaveChanges();
var error = new string[] {"Your deck has been successfully saved."};
return Ok(new { errors = new { success = error } });
}
return BadRequest(ModelState.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
));
}

EF Core Duplicate entry Exception

EF core throws an exception in the project I am working on
MySqlException: Duplicate entry '2' for key 'customers.IX_Customers_UserID'
UserID gives such an error when it is present I do not understand exactly what the error is, please help
public class Context : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Address> Addresses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//optionsBuilder.UseSqlite("Data Source = Shop.db");
//optionsBuilder.UseSqlServer(#"Data Source = (localdb)\v11.0; Initial Catalog=ShopDb; Integrated Security = SSPI;");
optionsBuilder.UseMySql(#"server=localhost;port=3306;database=ShopDb1;user=root;password=admin123;");
}
public Context()
{
Database.EnsureCreated();
}
}
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public Customer Customer { get; set; }
public List<Address> Addresses { get; set; }
}
public class Customer
{
public int ID { get; set; }
public int IdentifyNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public User User { get; set; }
[Required]
public int UserID { get; set; }
}
public class Suplier
{
public int ID { get; set; }
public string Name { get; set; }
public string TaxNumber { get; set; }
}
public class Address
{
public int ID { get; set; }
public string FullName { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public User User { get; set; }
public int UserID { get; set; }
}
public class Product
{
public int ProductID { get; set; }
[MaxLength(100)]
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
public int CategoryID { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
[MaxLength(100)]
[Required]
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var db = new Context())
{
var customer = new Customer()
{
IdentifyNumber = 123,
FirstName = "Remzi",
LastName = "Balakishiyev",
UserID = 2
};
db.Customers.Add(customer);
db.SaveChanges();
}
Console.ReadLine();
}
static void InsertUsers()
{
var users = new List<User> {
new User() { UserName ="Remzi",Email = "remzi.balakisiyev#gmail.com"},
new User() { UserName ="Xezri",Email = "xezri.balakisiyev#gmail.com"},
new User() { UserName ="Nurane",Email = "nurane.tarverdiyeva#gmail.com"}
};
using (var db = new Context())
{
db.Users.AddRange(users);
db.SaveChanges();
}
}
static void InsertAddresses()
{
var addresses = new List<Address> {
new Address(){FullName = "Remzi Balakisiyev", Title = "Ev addressi", Body = "Masalli",UserID=1},
new Address(){FullName = "Remzi Balakisiyev", Title = "Ish addressi", Body = "Baki",UserID=1},
new Address(){FullName = "Xezri Balakisiyev", Title = "Ev addressi", Body = "Masalli",UserID=2},
new Address(){FullName = "Nurane Tarverdiyeva", Title = "Ev addressi", Body = "Naxcivvan",UserID=3},
new Address(){FullName = "Rena Heyderova", Title = "Ev addressi", Body = "Xachmaz",UserID=2},
new Address(){FullName = "Memmed Bedelov", Title = "Ev addressi", Body = "Sumqayit",UserID=1}
};
using (var db = new Context())
{
db.Addresses.AddRange(addresses);
db.SaveChanges();
Console.WriteLine("Ishledi");
}
}
For each customer entity framework adds a new user with the primary key 2. To add a relationship to the user with id 2 you need to insert a user object to the user property.
var customer = new Customer()
{
IdentifyNumber = 123,
FirstName = "Remzi",
LastName = "Balakishiyev",
User = db.Users.FirstOrDefault(x => x.ID == 2)
};
db.Customers.Add(customer);
db.SaveChanges();

ASP.NET MVC 4 Code First Many to Many Adding to Collection

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.

Resources