How to modify database having foreign key in asp.net? - 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; }
}

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
});
}
}

Receiving AutoMapperMappingException

Currently I'm creating a new feature. It looks simple, but I am stuck at a problem with automapping dto to another one.
I have to create a wishlist [adding /deleting items of wishlist].
All works fine, except one thing: while adding an item to the wishlist, I'm get a message like this:
"type": "AutoMapperMappingException",
"message": "Error mapping types..."
However, I can see it got inserted into the database. Also, can delete it too. I understand the problem is linked to Automapper, but I could not figure out how to map correctly.
[HttpPost]
public async Task<IActionResult> Add(WishListItemCreationDto wishListItemDto)
{
var itemAdd = _mapper.Map<WishlistItemDto>(wishListItemDto);
var itemCreated = await _wishListItemService.AddAsync(itemAdd);
return CreatedAtAction(nameof(GetId), new { id = itemCreated.Id }, wishListItemDto);
}
//service
public async Task<WishlistItemDto> AddAsync(WishlistItemDto item)
{
var entity = _mapper.Map<WishlistItem>(item);
var entityDetails = await _productDetailsRepository.GetById(item.ProductDetailId);
entity.ProductDetails = entityDetails;
await _wishListItemRepository.AddAsync(entity);
return _mapper.Map<WishlistItemDto>(entity);
}
DTOs:
public class WishListItemCreationDto
{
[Required]
public string CustomerId { get; set; }
[Required]
public int ProductDetailId { get; set; }
[Min(1)]
[Required]
public int Quantity { get; set; }
}
public class WishlistItemDto
{
public int Id { get; set; }
public string CustomerId { get; set; }
public int ProductDetailId { get; set; }
public ProductDetailsDtoWithPrimaryImage ProductDetails { get; set; }
public int Quantity { get; set; }
}
public class WishlistItem
{
public int Id { get; set; }
public string CustomerId { get; set; }
public Customer Customer { get; set; }
public int ProductDetailsId { get; set; }
public ProductDetails ProductDetails { get; set; }
public int Quantity { get; set; }
}
ProductDetails DTO:
public class ProductDetails
{
public int Id { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
public IList<ProductAttributeValue> ProductAttributes { get; set; } = new List<ProductAttributeValue>();
public int Quantity { get; set; }
public string Sku => $"BRD{Id}";
public byte[] RowVersion { get; set; } = new byte[0];
}
public class ProductDetailsDtoWithPrimaryImage
{
public int Id { get; set; }
public int Quantity { get; set; }
public int ProductId { get; set; }
public ProductDisplayEntity Product { get; set; }
public IEnumerable<ProductAttributeWithValueDto> ProductAttributes { get; set; }
public byte[] RowVersion { get; set; }
public string Sku => $"BRD{Id}";
public int? PrimaryImageId { get; set; }
}
AutoMapper:
public WishlistItemProfile()
{
CreateMap<WishlistItem, WishListItemCreationDto>().ReverseMap();
CreateMap<WishlistItemDto, WishListItemCreationDto>().ReverseMap();
CreateMap<WishlistItem, WishlistItemDto>()
.ForMember(wi => wi.ProductDetailId, opt => opt.MapFrom(f => f.ProductDetailsId))
.ForMember(wi => wi.ProductDetails, opt => opt.MapFrom(f => f.ProductDetails))
.ReverseMap();
}
everything is okay, but you missed inner mapping of your classes.
What the error says:
Mapping types:
ProductDetailsDtoWithPrimaryImage -> ProductDetails
SimpleWebApi.Controllers.ProductDetailsDtoWithPrimaryImage -> SimpleWebApi.Controllers.ProductDetails
Add additional mapping in your constructor WishlistItemProfile
CreateMap<ProductDetails, ProductDetailsDtoWithPrimaryImage>().ReverseMap();
And it starts works perfect

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()
));
}

MVC one to many user companies and notifiaction

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

Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market'

I am getting the following error
Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market'
private CellSite MapEntityToCellSitePOCO(t_CellSite _cellsite)
{
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region.RegionId = _cellsite.RegionId;
return cellsite;
}
the following is my datacontracts file
public class CellSite
{
public Guid CellSiteID { get; set; }
public string SiteId { get; set; }
public Region Region { get; set; }
public Market Market { get; set; }
public Guid? ConstructionManager { get; set;}
}
This is market.cs
public class Market
{
public Guid? MarketID { get; set; }
public string OperatorMarketName { get; set; }
public string MarketName { get; set; }
public decimal AllOtherAmount { get; set; }
public decimal RawLandAmount { get; set; }
public decimal RenewalFee { get; set; }
public bool IsActive { get; set; }
}
there is a column MarketId in cellsite table which i want to bring on.how can i do that? I am new to entity frame work.
thanks in advance
You have to initialize your Market and Region properties first:
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market = new Market();
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region = new Region();
cellsite.Region.RegionId = _cellsite.RegionId;

Resources