I have a class called Item which references the next item and the previous item.
public class Item
{
private Item() { }
public Item(string itemName)
{
ItemId = Guid.NewGuid();
ItemName = itemName;
}
public Guid ItemId { get; set; }
public string ItemName { get; set; }
public Guid NextItemId { get; set; }
public virtual Item NextItem { get; set; }
public Guid PreviousItemId { get; set; }
public virtual Item PreviousItem { get; set; }
public Guid GroupId { get; set; }
public virtual Group Group { get; set; }
}
I have another table called Group it is for grouping it items.
public class Group
{
private Group() { }
public Group(string groupName)
{
GroupId = Guid.NewGuid();
GroupName = groupName;
GroupItems = new List<Item>();
}
public void AddGroupItem(Item item)
{
if (Items.Count == 0)
{
Items.Add(item);
}
else
{
item.PreviousItem = Items.Last();
item.PreviousItemId = Items.Last().ItemId;
Items.Last().NextItem = item;
Items.Last().NextItemId = item.ItemId;
Items.Add(item);
}
}
public Guid GroupId { get; set; }
public string GroupName { get; set; }
public virtual IList<GroupItem> GroupItems { get; set; }
}
Here's how I create and save items and their group.
Group group1 = new Group("first group");
Item item1 = new Item("item 1");
Item item2 = new Item("item 2");
Item item3 = new Item("item 3");
group1.AddItem(item1);
group1.AddItem(item2);
group1.AddItem(item3);
_context.Add(group1);
_context.SaveChanges();
How do I write the OnModelCreating to handle the two references to the same table.
You can do it in next way. First of all you should add two new properties to you model public virtual List<Item> ParentNextItems { get; set; } and public virtual List<Item> ParentPreviousItems { get; set; }. So your model will be something like this
public class Item
{
private Item() { }
public Item(string itemName)
{
ItemId = Guid.NewGuid();
ItemName = itemName;
}
public Guid ItemId { get; set; }
public string ItemName { get; set; }
public Guid? NextItemId { get; set; }
public virtual Item NextItem { get; set; }
public virtual List<Item> ParentNextItems { get; set; }
public Guid? PreviousItemId { get; set; }
public virtual Item PreviousItem { get; set; }
public virtual List<Item> ParentPreviousItems { get; set; }
}
And than you can configure it in next way
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Item>()
.HasKey(x => x.ItemId);
modelBuilder.Entity<Item>()
.HasOne(x => x.NextItem).WithMany(x => x.ParentNextItems).HasForeignKey(x => x.NextItemId)
.Metadata.DeleteBehavior = DeleteBehavior.Restrict;
modelBuilder.Entity<Item>()
.HasOne(x => x.PreviousItem).WithMany(x => x.ParentPreviousItems).HasForeignKey(x => x.PreviousItemId)
.Metadata.DeleteBehavior = DeleteBehavior.Restrict;
base.OnModelCreating(modelBuilder);
}
That's all. But if you want to achieve the same with attribute configuration, than you can skip void OnModelCreating(ModelBuilder modelBuilder) changes and just write next model:
public class Item
{
private Item() { }
public Item(string itemName)
{
ItemId = Guid.NewGuid();
ItemName = itemName;
}
[Key]
public Guid ItemId { get; set; }
public string ItemName { get; set; }
public Guid? NextItemId { get; set; }
[ForeignKey(nameof(NextItemId))]
[InverseProperty(nameof(ParentNextItems))]
public virtual Item NextItem { get; set; }
[ForeignKey(nameof(NextItemId))]
public virtual List<Item> ParentNextItems { get; set; }
public Guid? PreviousItemId { get; set; }
[ForeignKey(nameof(PreviousItemId))]
[InverseProperty(nameof(ParentPreviousItems))]
public virtual Item PreviousItem { get; set; }
[ForeignKey(nameof(PreviousItemId))]
public virtual List<Item> ParentPreviousItems { get; set; }
}
Update
Also you should make PreviousItemId, NextItemId optional (Guid?), I did corresponding changes in my answer.
And as far as I know, you just can't do it in one .SaveChanges() trip. When you create your second item you should already have first item saved into database. (anyway this is subject for another question)
But anyway if you modify you code to something like that
Group group1 = new Group("first group");
_context.Add(group1);
Item item1 = new Item("item 1");
group1.AddItem(item1);
_context.SaveChanges();
Item item2 = new Item("item 2");
group1.AddItem(item2);
_context.SaveChanges();
Item item3 = new Item("item 3");
group1.AddItem(item3);
_context.SaveChanges();
You can do it in one transaction
You don't need to have Collection, since as far I understand here you aim to create some type of Two Way LinkedList. A was able to fix it by adding .HasOne() to the main model.
modelBuilder.Entity<Item>().HasOne(x => x.NextItem);
modelBuilder.Entity<Item>().HasOne(x => x.PreviousItem);
public int? DeaultNextStateId { get; set; }
public State DeaultNextState { get; set; }
public virtual ICollection<State> DeaultNextStates { get; set; }
public int? OkNextStateId { get; set; }
public State OkNextState { get; set; }
public virtual ICollection<State> OkNextStates { get; set; }
public int? NotOkNextStateId { get; set; }
public State NotOkNextState { get; set; }
public virtual ICollection<State> NotOkNextStates { get; set; }
modelBuilder.Entity<Models.Workflow.State>()
.HasKey(x => x.Id);
modelBuilder.Entity<Models.Workflow.State>()
.HasOne(x => x.DeaultNextState).WithMany(x => x.DeaultNextStates).HasForeignKey(x => x.DeaultNextStateId)
.Metadata.DeleteBehavior = DeleteBehavior.Restrict;
modelBuilder.Entity<Models.Workflow.State>()
.HasOne(x => x.OkNextState).WithMany(x => x.OkNextStates).HasForeignKey(x => x.OkNextStateId)
.Metadata.DeleteBehavior = DeleteBehavior.Restrict;
modelBuilder.Entity<Models.Workflow.State>()
.HasOne(x => x.NotOkNextState).WithMany(x => x.NotOkNextStates).HasForeignKey(x => x.NotOkNextStateId)
.Metadata.DeleteBehavior = DeleteBehavior.Restrict;
Related
I have entity
public class ImageTeam
{
public int Id { get; set; }
public int TeamID { get; set; }
public Team Team { get; set; }
public int PostTeamID { get; set; }
public string Image { get; set; }
public int ImageType { get; set; }
public int StatusPublic { get; set; }
public int StatusActive { get; set; }
public DateTime CreatedAt { get; set; }
}
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public int NoMember { get; set; }
public float Score { get; set; }
public int StatusActive { get; set; }
public int TeamType { get; set; }
public virtual List<TeamGroup> ListMember { get; set; }
public virtual List<ImageTeam> ListAvatar { get; set; }
public virtual List<ImageTeam> ListBanner { get; set; }
public DateTime CreatedAt { get; set; }
}
config data context
modelBuilder.Entity<Team>(entity =>
{
entity.HasMany(x => x.ListAvatar)
.WithOne(t => t.Team)
.HasForeignKey(pv => pv.TeamID);
});
when I post the data insert a new record entity ImageTeam then it show exception
I need to do...Help me
In the Team class you add another relation ListBanner to ImageTeam class ,you have not set an foreign key for it, so EF automatically creates a TeamID and because TeamId already in the class, it's throw exception . You also need to set an foreign key for second relation.
public class ImageTeam
{
public int Id { get; set; }
public int TeamID { get; set; }
public Team Team { get; set; }
public int BannerTeamId { get; set; }
public Team BannerTeam { get; set; }
public int PostTeamID { get; set; }
public string Image { get; set; }
public int ImageType { get; set; }
public int StatusPublic { get; set; }
public int StatusActive { get; set; }
public DateTime CreatedAt { get; set; }
}
entity.HasMany(x => x.ListAvatar)
.WithOne(t => t.Team)
.HasForeignKey(pv => pv.TeamID).OnDelete(DeleteBehavior.Restrict);
entity.HasMany(x => x.ListBanner)
.WithOne(t => t.BannerTeam)
.HasForeignKey(pv => pv.BannerTeamId).OnDelete(DeleteBehavior.Restrict);
I have found a solution:
edit Team entity:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public int NoMember { get; set; }
public float Score { get; set; }
public int StatusActive { get; set; }
public int TeamType { get; set; }
public virtual List<TeamGroup> ListMember { get; set; }
public virtual List<ImageTeam> ListImage { get; set; }
public DateTime CreatedAt { get; set; }
}
*no config data context
create new model: TeamViewModel
public class TeamViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int NoMember { get; set; }
public float Score { get; set; }
public int StatusActive { get; set; }
public int TeamType { get; set; }
public virtual List<TeamGroupViewModel> ListMember { get; set; }
public virtual List<ImageTeam> ListImage { get; set; }
public string AvatarUrl { get; set; }
public virtual List<ImageTeam> ListAvatar { get; set; }
public string BannerUrl { get; set; }
public virtual List<ImageTeam> ListBanner { get; set; }
public virtual List<ImageTeam> ListPost { get; set; }
}
in controller :
[Route("api/[controller]/{id}/view")]
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var team = _teamService.GetById(id);
var model = _mapper.Map<TeamViewModel>(team);
model = parserImageTeam(model);
return Ok(model);
}
[Route("api/[controller]/{UserId}/view-teams")]
[HttpGet("{UserId}")]
public IActionResult GetAllTeamOfUser(int UserId)
{
// list teams
var teams = _teamService.GetTeamOfUser(UserId);
var _teams = _mapper.Map<IList<TeamViewModel>>(teams);
var newTeams = new List<TeamViewModel>();
foreach (TeamViewModel team in _teams)
{
newTeams.Add(parserImageTeam(team));
}
return Ok(newTeams);
}
private TeamViewModel parserImageTeam(TeamViewModel teamModel)
{
var imageAvatars = new List<ImageTeam>();
var imageBanners = new List<ImageTeam>();
var imagePosts = new List<ImageTeam>();
bool avt = false, banner = false;
foreach (ImageTeam image in teamModel.ListImage)
{
if (image.ImageType == Constants.ImageType.IMAGE_AVATAR_TEAM)
{
image.Image = parserUrlImage(image);
imageAvatars.Add(image);
if (!avt)
{
teamModel.AvatarUrl = image.Image;
avt = true;
}
}
if (image.ImageType == Constants.ImageType.IMAGE_BANNER_TEAM)
{
image.Image = parserUrlImage(image);
imageBanners.Add(image);
if (!banner)
{
teamModel.BannerUrl = image.Image;
banner = true;
}
}
if (image.ImageType == Constants.ImageType.IMAGE_POST_TEAM)
{
image.Image = parserUrlImage(image);
imagePosts.Add(image);
banner = true;
}
}
teamModel.ListAvatar = imageAvatars;
teamModel.ListBanner = imageBanners;
teamModel.ListPost = imagePosts;
return teamModel;
}
private string parserUrlImage(ImageTeam model)
{
string url = Configuration.GetValue<string>("BaseVariables:BaseUrl");
// another controller handle request (ImagesController)
return model.Image = url + "/Images/" + Constants.ImageType.getFolderName(model.ImageType).ToLower() + "/" + model.TeamID + "?ImageType=" + model.ImageType + "&imageName=" + model.Image;
}
I am new to Entity Framework Core 3.1 and trying to define the one-to-many relationship between two tables. I am currently struggling and getting compilation errors. Could somebody tell me what the problem could be.
The error is:
PersonNote does not contain the definition for PersonNote
I am currently getting is at line
entity.HasOne(d => d.PersonNote)
How else could I define one-to-many relationship?
The two tables are Person and PersonNote. One Person can have many PersonNotes. I have defined the models for them
public class Person
{
public int Id { get; set; }
public int? TitleId { get; set; }
public string FirstName { get; set; }
public string FirstNamePref { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Gender { get; set; }
public int AddressId { get; set; }
public string TelephoneNumber { get; set; }
public string MobileNumber { get; set; }
public string Email { get; set; }
public int? PartnerId { get; set; }
public bool Enabled { get; set; }
public string CreatedBy { get; set; }
public DateTime Created { get; set; }
public string ModifiedBy { get; set; }
public DateTime Modified { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime RecordStartDateTime { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime RecordEndDateTime { get; set; }
public Address Address { get; set; }
public Title Title { get; set; }
public Client Client { get; set; }
internal static IEnumerable<object> Include(Func<object, object> p)
{
throw new NotImplementedException();
}
public PersonNote PersonNote { get; set; }
}
public class PersonNote
{
public int Id { get; set; }
public int PersonId { get; set; }
public string Note { get; set; }
public int AuthorId { get; set; }
public string CreatedBy { get; set; }
public DateTime Created { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime RecordStartDateTime { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime RecordEndDateTime { get; set; }
}
public IEnumerable<PersonNote> GetPersonNotes(int personId)
{
var PersonNotes = PersonNote
.Include(x => x.)
.Where(x => x.Id == personId)
.ToList();
return PersonNotes;
}
I have tried the following in OnModelCreating:
modelBuilder.Entity<PersonNote>(entity =>
{
entity.ToTable("PersonNote", "common");
entity.HasOne(d => d.PersonNote)
.WithMany(p => p.Person)
.HasForeignKey(d => d.PersonId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_commonPersonNote_commonPerson");
});
You should have have something like this (other properties are omitted):
class Person
{
[Key]
public int Id { get; set; }
public List<PersonNote> PersonNotes { get; set; }
}
class PersonNote
{
[Key]
public int Id { get; set; }
public int PersonId { get; set; }
}
class StackOverflow : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<PersonNote> PersonNotes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasMany(p => p.PersonNotes)
.WithOne()
.HasForeignKey(p => p.PersonId);
}
}
I am trying to query EF models. (GameBank and GameCouponBank) How can I make a projection for left outer join (GoupJoin)?
Can I make projection for Coupons?
Here is my query
var gameBankResult = context.GameBanks.GroupJoin(context.GameCouponBanks, g => g.GameBankID, gc => gc.GameBankID,
(g,gc) => new {
g.quantity,
g.currency,
g.initiationResultCode,
g.productCode,
g.productDescription,
g.referenceId,
g.responseDateTime,
g.unitPrice,
g.totalPrice,
Coupons = gc
})
.Where(g => g.productCode == initiate.productCode)
.Select(s => s);
Here is models:
public class GameBank
{
public int GameBankID { get; set; }
public string referenceId { get; set; }
public string productCode { get; set; }
public int quantity { get; set; }
public string version { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public int? customerID { get; set; }
public string password { get; set; }
public DateTime? responseDateTime { get; set; } = DateTime.Now;
public string initiationResultCode { get; set; }
public string companyToken { get; set; }
public int used { get; set; }
public string productDescription { get; set; }
public string currency { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public virtual List<GameCouponBank> coupons { get; set; }
}
public class GameCouponBank
{
public int Id { get; set; }
public int GameBankID { get; set; }
public DateTime? expiryDate { get; set; }
public string Serial { get; set; }
public string Pin { get; set; }
}
You don't need to use GroupJoin explicitly. You can simply project your query as follows:
var gameBankResult = context.GameBanks.Where(g => g.productCode == initiate.productCode)
.Select(g => new {
g.quantity,
g.currency,
g.initiationResultCode,
g.productCode,
g.productDescription,
g.referenceId,
g.responseDateTime,
g.unitPrice,
g.totalPrice,
Coupons = g.coupons.Select(c => new {c.Id, c.GameBankID,...}).ToList() //<-- Here is the projection for coupons
}).FirstOrDefault(); // I assume you are returning single entity, if not then use `.ToList()` instead of `.FirstOrDefault()`
I have five tables in database whose Entity classes are as follows -
Product
public int ProductId { get; set; }
public string Name { get; set; }
public int Category { get; set; }
public string Description { get; set; }
public string Brand { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
public virtual ICollection<ProductImage> ProductImages { get; set; }
public virtual ICollection<ProductVariantMapping> ProductVariantMappings
ProductCategory
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
ProductImage
public int ProductImageId { get; set; }
public int ProductId { get; set; }
public byte[] Image { get; set; }
public virtual Product Product { get; set; }
ProductVariantMapping
public int MappingId { get; set; }
public int ProductId { get; set; }
public int ProductVariantId { get; set; }
public string Value { get; set; }
public System.Guid GUID { get; set; }
public virtual Product Product { get; set; }
public virtual ProductVariant ProductVariant { get; set; }
ProductVariant
public int ProductVariantId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<ProductVariantMapping> ProductVariantMappings
I want to get Product Details which should include ProductId, ProductName, Category, Description, Brand, Image(Only 1 for now), and Variants*
*Variants would be a list of all the variants of a product. A single variant can be a combination of all the VariantIds with same GUIDs. (VariantName is in ProductVariant table and VariantValue is in ProductVariantMapping table and Price is in inventory table).
So, I used method-based linq for this purpose.
EkartEntities ekartEntities = new EkartEntities();
var productDetails = ekartEntities.Products.Include(p =>
p.ProductVariantMappings).Include(p => p.ProductImages).Include(p =>
p.ProductCategory).Where(p => p.ProductId ==
productDetailDTO.ProductId).ToList();
Now I have to convert my product into a ProductDetailDTO.
ProductDetailDTO
public class ProductDetailDTO
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public byte[] Image { get; set; }
public string Description { get; set; }
public string Brand { get; set; }
public List<Variant> Variants { get; set; }
}
public class Variant
{
public string Name { get; set; }
public string Value { get; set; }
public System.Guid Guid { get; set; }
public decimal Price { get; set; }
}
I started doing this like this -
void ToDTO(List<Product> products)
{
EkartEntities ekartEntities = new EkartEntities();
ProductDetailDTO productDetailDTO = new ProductDetailDTO();
foreach (var item in products)
{
productDetailDTO.ProductId = item.ProductId;
productDetailDTO.Name = item.Name;
productDetailDTO.Category = item.ProductCategory.Name;
productDetailDTO.Description = item.Description;
productDetailDTO.Brand = item.Brand;
productDetailDTO.Image = item.ProductImages.ElementAt(0).Image;
foreach (var variant in item.ProductVariantMappings)
{
productDetailDTO.Variants = variant.ProductVariant // ?
}
}
}
I don't know how do I proceed further. How can I extract the variant based on the GUIDs?
The logic of combining of ProductVariant entries with same GUID in mapping table doesn't seem clear from the question, however you can group entries in ProductVariantMappings by GUID and then add any logc you like on group. Here is an example where I take first name and value in a groub of variant with the same GUID:
void ToDTO(List<Product> products)
{
EkartEntities ekartEntities = new EkartEntities();
ProductDetailDTO productDetailDTO = new ProductDetailDTO();
foreach (var item in products)
{
productDetailDTO.ProductId = item.ProductId;
productDetailDTO.Name = item.Name;
productDetailDTO.Category = item.ProductCategory.Name;
productDetailDTO.Description = item.Description;
productDetailDTO.Brand = item.Brand;
productDetailDTO.Image = item.ProductImages.ElementAt(0).Image;
productDetailDTO.Variants = item.ProductVariantMappings
.GroupBy(pm => pm.GUID)
.Select(g => new Variant
{
Guid = g.Key,
// Here should be some logic for getting a name of the combination of Variants
// I just take first
Name = g.FirstOrDefault()?.ProductVariant?.Name,
// Here should be some logic for getting a value of the combination of Variants
// Take first again
Value = g.FirstOrDefault()?.Value,
Price = // need inventory table to compute price
})
.ToList();
}
}
Also note that you need somehow add relation to inventory table, which is not presented in question. Hope it helps.
What is the best solutions to retrieve records from child table in relation?
I cannot include the solution file in this question.
Model
[Table("Tbl_DefaultValue")]
public class DefaultValue
{
[Key]
public int DefaultValue_ID { get; set; }
public string DefaultVal_Name { get; set; }
public virtual ICollection<DefaultValue_Det> DefaultValue_Det { get; set; }
}
[Table("Tbl_DefaultValue_Det")]
public class DefaultValue_Det
{
[Key]
public int DefaultValue_Det_ID { get; set; }
public int DefaultValue_ID { get; set; }
public string DefaultValue_Value { get; set; }
public virtual DefaultValue DefaultValue { get; set; }
public virtual ICollection<Car> Cars { get; set; }
}
Controller
driverdt.TypeList =
new SelectList(db.DefaultValue_Det
.Where(a => a.DefaultValue_ID == db.DefaultValue
.Where(d => d.DefaultVal_Name == "marid")
.Max(b=>b.DefaultValue_ID)), "DefaultValue_Det_ID", "DefaultValue_Value");
return View( driverdt);
You can pre-populate collection DefaultValue_Det using FetchMany:
driverdt.TypeList =
new SelectList(db.DefaultValue_Det
.Where(a => a.DefaultValue_ID == db.DefaultValue
.Where(d => d.DefaultVal_Name == "marid")
.Max(b=>b.DefaultValue_ID))
.FetchMany(x => x.DefaultValue_Det)
, "DefaultValue_Det_ID", "DefaultValue_Value");