Entity Framework assign multiple foreign key - code first approach - foreign-keys

I don't know how to add two foreign key in the following scenario:
I have two tables, one exists in the database yet (table Market), and I have to create a new table (MarketBranch).
Table Market:
public class Market
{
public Int16 MarketId { get; set; }
public string MarketName { get; set; }
}
Table MarketBranch:
public partial class MarketBranch : BaseModelSingleUserNullable
{
public Int16 HoldingMarketId { get; set; }
public Int16 BranchMarketId { get; set; }
}
Values in table must necessarily be the market ids present in the Market table, so I am not sure how to assign foreign keys before doing add-migration
What I mean is that for example I have 3 Markets (Italy with id 1, Germany with id 2 and France with id 3)

I found the way to solve it, I just have to write, in MarketBranch:
public partial class MarketBranch : BaseModelSingleUserNullable
{
public Int16 HoldingMarketId {get;set;}
public Int16 BranchMarketId {get;set;}
public virtual Market HoldingMarket { get; set; }
public virtual Market BranchMarket{ get; set; }
}
Then, in DbContext:
public virtual DbSet<MarketBranch> MarketBranches { get; set; }
modelBuilder.Entity<MarketBranch>(entity => entity.HasNoKey());
modelBuilder.Entity<MarketBranch>().HasQueryFilter(p => !p.Deleted);
And last:
Add-Migration MarketBranchTable
Update-Database

Related

How to retrieve list from DB to front-end with AutoMapper

After changing the mapping to Automapper, only an empty list is sent through the endpoint.
Initially I had an endpoint that retrieved all employees with info including a list with every course each employee had taken. This was with manual mapping between entities & Dto.
//From startup.cs in Configure
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Employee, Models.EmployeeCoursesDto>();
cfg.CreateMap<Employee, Models.EmployeeDto>();
cfg.CreateMap<EmployeeCourses, Models.EmployeeCoursesDto>();
});
//From Employee entity
public class Employee
{
[Key]
//Gen new Id key in DB when object created
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(50)]
public string Title { get; set; }
public ICollection<EmployeeCourses> EmployeeCourses { get; set; }
= new List<EmployeeCourses>();
}
}
//From employee Dto
public class EmployeeDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public ICollection<EmployeeCoursesDto> EmployeeCourses { get; set; }
= new List<EmployeeCoursesDto>();
}
}
//Endpoint in controller
[HttpGet()]
public IActionResult GetAllEmployees()
{
var employeeEntities = _employeeInfoRepository.GetEmployees();
var results = Mapper.Map<IEnumerable<EmployeeDto>>(employeeEntities);
return Ok(results);
}
//From Irepository
IEnumerable<Employee> GetEmployees();
//From repository
public IEnumerable<Employee> GetEmployees()
{
return _context.Employees.OrderBy(c => c.Name).ToList();
}
I expected output all employees with all datafileds, including their list of courses.
The output is all fields with data, except the list of courses which is "0" when running with a breakpoint, and in Postman it shows as only:
"id": 2,
"name": "Test Person",
"title": "Bus Driver",
"numberOfCourses": 0,
"employeeCourses": [],
"totalAchievedHoursAuditor": 0,
"totalAchievedHoursAccountant": 51,
"courseBalanceAccountant": null,
"courseBalanceAuditor": null
However, if I try another endpoint only for retrieving a specific course, or a list of courses, the data show correctly. Seems there are an issue with mapping the employees & courses at the same time?
I found the error, not Automapper, but my Linq statement:
return _context.Employees.Include(c => c.EmployeeCourses).ToList();
Please close this thread. Thanks for the reply Lucian Bargaoanu & have a great weekend.

I want no Parent entity or foreign key on the Grandchild entity

I have three entities, BaseEntity, Child and GrandChild, that are predictably linked together.
It goes like this:
public class BaseEntity
{
public string CompanyId { get; set; }
public string BaseEntityId { get; set; }
public virtual List<Child> Children { get; set; }
}
public class Child
{
public string CompanyId { get; set; }
public string BaseEntityId { get; set; }
public string ChildId { get; set; }
public virtual BaseEntity Parent { get; set; }
public virtual List<GrandChild> GrandChildren { get; set; }
}
public class GrandChild
{
public string CompanyId { get; set; }
public string BaseEntityId { get; set; }
public string ChildId { get; set; }
public string GrandChildId { get; set; }
public virtual Child ParentChild { get; set; }
}
public class BaseContext : DbContext
{
protected override void OnModelCreating(ModelBuilder p_mbuModel)
{
p_mbuModel.Entity<BaseEntity>().ToTable("T_BaseEntity");
p_mbuModel.Entity<BaseEntity>().HasKey(t => new { t.CompanyId, t.BaseEntityId });
p_mbuModel.Entity<Child>().ToTable("T_Child");
p_mbuModel.Entity<Child>().HasKey(t => new { t.CompanyId, t.BaseEntityId, t.ChildId });
p_mbuModel.Entity<Child>().HasOne(c => c.Parent).
WithMany(p => p.Children).
HasForeignKey(c => new { c.CompanyId, c.BaseEntityId }).
HasConstraintName("FK_Child_BaseEntity");
p_mbuModel.Entity<GrandChild>().ToTable("T_GrandChild");
p_mbuModel.Entity<GrandChild>().HasKey(t => new { t.CompanyId, t.BaseEntityId, t.ChildId, t.GrandChildId });
p_mbuModel.Entity<GrandChild>().HasOne(gc => gc.ParentChild).
WithMany(c => c.GrandChildren).
HasForeignKey(gc => new { gc.CompanyId, gc.BaseEntityId, gc.ChildId }).
HasConstraintName("FK_GrandChild_Child");
}
}
You'll note that it features no direct link from GrandChild to BaseEntity and no foreign key between GrandChild and BaseEntity. Which is consistent. I don't want that direct link. (If nothing else, it could lead to unpleasantness with cascading deletions.)
Still, when I launch Add-Migration, I get the following:
table.ForeignKey(
name: "FK_T_GrandChild_T_BaseEntity_BaseEntityId",
columns: x => { x.CompanyId, x.BaseEntityId },
principalTable: "T_BaseEntity",
principalColumns: new { "CompanyId", "BaseEntityId" },
onDelete: ReferentialAction.Cascade);
The very thing that I have tried to keep out. (On migrating, it creates the foreign key constraint that I don't want, and with that unwieldy name to boot.)
I have tried adding
    p_mbuModel.Entity<GrandChild>().Ignore(t => new { t.CompanyId, t.BaseEntityId });
which raises an exception to the tune of
The expression 't => new <>f__AnonymousType10`2(CompanyId = t.CompanyId, BaseEntityId = t.BaseEntityId)' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'.
(I guess that's to be expected; that was a long shot on my behalf.)
I could add a GrandParent property to GrandChild and use Ignore() on it, but that would require me to create the very link I want to hide.
I want no link between BaseEntity and GrandChild, neither as entities nor as database tables.
How can I achieve this?
... I'm embarrassed to admit this. When I posted the question, I trimmed the irrelevant parts of my classes. And I didn't notice that BaseEntity included this line:
public virtual List<GrandChild> GrandChildren { get; set; }
I removed it and launched Add-Migration again. No link appeared between BaseEntity and GrandChild.
Apologies to any and all who tried to make sense of this incomplete riddle.

EF Core - Fluent API many-to-many self reference

I am attempting to configure 2 classes fluently.
public class Company
{
[Key]
public int Id {get; set; }
public string Name { get; set; }
public List<CompanyOwnership> OwnedBy { get; set; }
}
public class CompanyOwnership
{
public static void Configure(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CompanyOwnership>()
.HasOne(cpo => cpo.OwnedCompany)
.WithMany(cp => cp.OwnedBy)
.HasForeignKey(cpo => cpo.OwnedCompanyId);
modelBuilder.Entity<CompanyOwnership>()
.HasOne(cpo => cpo.OwningCompany)
.WithMany()
.HasForeignKey(cpo => cpo.OwningCompanyId);
}
[Key]
public int Id {get; set; }
public int OwnedCompanyId { get; set; }
public Company OwnedCompany { get; set; }
public int OwningCompanyId { get; set; }
public Company OwningCompany { get; set; }
public decimal Percentage { get; set; }
}
The above code will result in an error:
InvalidOperationException: Unable to determine the relationship
represented by navigation property 'Company.OwnedBy' of type
'List<CompanyOwnership>'. Either manually configure the relationship,
or ignore this property using the '[NotMapped]' attribute or by using
'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Could I get some input about why the above setup is not enough?
Thank you,
Nvm,
it turned out that I forgot to call Configure(...).
It is working fine now.

Sitecore Glass Mapper ObjectToSwitchTo null reference in page editor

I have the following structure as Template in visual studio :
Under a page, i have one or more link root
[SitecoreType(TemplateId = "{4AAA9A10-36C2-484F-A648-2BEF349F0052}", AutoMap = true)]
public class LinkRoot : IBaseTemplate
{
[SitecoreChildren(InferType = true)]
public virtual IEnumerable<LinkItem> Children { get; set; }
[SitecoreInfo(SitecoreInfoType.TemplateId)]
public virtual Guid TemplateId { get; set; }
public Guid Id { get; set; }
public string Language { get; set; }
public ItemUri Uri { get; set; }
public int Version { get; private set; }
}
Under the link root i've LinkItems
[SitecoreType(AutoMap = true)]
public class LinkItem : IBaseTemplate
{
[SitecoreField("Link Name")]
public virtual string LinkName { get; set; }
[SitecoreField("Link")]
public virtual Link Link { get; set; }
public Guid Id { get; set; }
public string Language { get; set; }
public ItemUri Uri { get; set; }
public int Version { get; private set; }
}
I display those items in a view like that :
#foreach (var link in Model.Children.Where(o => o.TemplateId.Equals(TemplateIDs.LinksRoot.Guid)))
{
foreach (var linkChildren in link.Children)
{
using (BeginRenderLink(linkChildren, x => x.Link, isEditable: true))
{
#Editable(linkChildren, x => x.LinkName)
}
}
}
It works great, i can see my links with the good name etc, but when i go to the page editor i got this error :
Value cannot be null. Parameter name: objectToSwitchTo
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.Common.Switcher2.Enter(TValue objectToSwitchTo)
at Sitecore.Data.Items.ContextItemSwitcher..ctor(Item item)
at Glass.Mapper.Sc.GlassHtml.MakeEditable[T](Expression1 field, Expression`1 standardOutput, T model, Object parameters, Context context, Database database, TextWriter writer)
Does someone already experienced that or have an idea why i have this error ?
Thanks
I think it means that Glass can't resolve the template of the LinkItem model.
Instead of:
[SitecoreType(AutoMap = true)]
public class LinkItem : IBaseTemplate
Try to explicitly define the template ID:
[SitecoreType(TemplateId = "{your-template-guid}", AutoMap = true)]
public class LinkItem : IBaseTemplate
I think this might be a bug, can you log it on github as an issue.

Microsoft Moles : circular reference error?

I've the following Entity Framework entities:
public class Country
{
public long Id { get; set; }
public string Code { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
public class Person
{
public long Id { get; set; }
public long? Country_Id { get; set; }
public Country HomeCountry { get; set; }
}
Moles has generated MPerson and MCountry stub classes.
Now I do want to stub the set of the Country_Id:
MPerson.AllInstances.Country_IdSetNullableOfInt64 = (Person instance, long? id) =>
{
// Do something
// Set the Country_Id to the provided id
// This will trigger this same method again and again. How to avoid this ?
instance.Country_Id = id;
};
This post gives the answer:
MolesContext.ExecuteWithoutMoles(() => instance.Country_Id = id);