How can I get all the objects associated through the intermediate table by ServiceStack.OrmLite? - ormlite-servicestack

I'm a beginner who has just started using ServiceStack.OrmLite. I have a question. How can I get all the objects associated through the intermediate table?
details as following:
Public class book
{
    Public int id { get; set; }
    Public string name { get; set; }
    [Reference]
    Public List<bookusers> bookusers { get; set; }
}
Public class bookusers
{
    Public int id { get; set; }
    Public int bookid { get; set; }
    Public int userid { get; set; }
    [Reference]
    Public book book { get; set; }
    [Reference]
    Public user userObject { get; set; }
}
Public class user
{
    Public int id { get; set; }
    Public int age { get; set; }
    [Reference]
    Public List<bookusers> userbooks { get; set; }
}
var model = db.LoadSingleById<book>(id);
db.LoadReferences(model);
// model.bookusers[0].userObject is null

You can't directly retrieve second level references as stated in documentation.
Loads related data only 1-reference-level deep
A quick and dirt working method could be the next
var model = db.LoadSingleById<book>(id);
if (model.bookusers != null && model.bookusers.Any())
{
foreach (var bookUser in model.bookusers)
{
db.LoadReferences(bookUser);
}
}
Then you should have your userObject property populated.

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

Save Relation between User and Entity in ASP.NET MVC4

I have an Exercise entity defined in my ASP.NET MVC4 Web Application.
I'm using the Form Authentication with the default AccountModels.cs class.
I have class which looks like
public class Exercise
{
private DateTime _DateCreated = DateTime.Now;
private UserProfile _Teacher;
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public DateTime Date
{
get { return _DateCreated; }
set { _DateCreated = value; }
}
public UserProfile Author
{
get { return _Teacher; }
set { _Teacher = value; }
}
}
Am I using the UserProfile correctly to link between an Exercise and a logged in user?
How can I get the current UserProfile in my controller?
Change it like this:
public class Exercise
{
public Exercise()
{
this.Date = DateTime.Now;
this.Author = User.Identity.Name; //Write this line if you want to set
//the currently logged in user as the Author
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public virtual DateTime Date { get; set; }
public virtual UserProfile Author { get; set; }
}

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