multiple tables mapping entity framework code first - entity-framework

I have 3 Entities Roles, Modules and Permissions and I am following code first approach using EF 6
Roles has RoleID , Modules has ModuleID and Permissions has PermissionID as Keys.
Now I want Map these 3 ID values to another mapping table RoleAccess on creating Role
I am able to map entity to with ICollection property and the same is not working for the above scenario.
help me out with code suggestions...
The configuration i am trying add is below..
'this is the mapping configuration i am trying `this.ToTable("Roles");
//this.HasKey(c => c.Id)
// .HasMany(c => c.Permissions)
// .WithRequired()
// .HasForeignKey(c => new { c.SubModuleId, c.EntitlementTypeId });
this.HasMany(a => new[] {a.SubModules,a.EntitlementTypes})
.WithMany(b => b.Roles)
.Map(mc =>
{
mc.ToTable("Permissions");
mc.MapLeftKey("RoleId");
mc.MapRightKey(new[] { "SubModuleId", "EntitlementTypeId" });
});`'

Related

How to Exclude from migration Auto-Generated table in EF?

i have table Asp_net_users which is many-to-many relation with table Clients. There are no mapped object in between them, it been auto -generated by EF:
modelBuilder.Entity<Client>(entity =>
{
entity.Property(e => e.State)
.HasConversion<string>();
entity.HasMany(d => d.Users)
.WithMany(p => p.Clients)
.UsingEntity<Dictionary<string, object>>(
"ClientUser",
l => l.HasOne<AspNetUser>().WithMany().HasForeignKey("UserId"),
r => r.HasOne<Client>().WithMany().HasForeignKey("ClientId"),
j =>
{
j.HasKey("ClientId", "UserId");
j.ToTable("client_users"); // ,"identity"
j.IndexerProperty<string>("ClientId");
j.IndexerProperty<string>("UserId");
});
});
The code above generating table client_users which i don't want in my migration.
I've tried to add to code above:
.Metadata
.SetIsTableExcludedFromMigrations(true)
no luck.
I know I can exclude using this method
modelBuilder.Entity<AspNetUser>().ToTable("asp_net_users", "identity", t => t.ExcludeFromMigrations());
but the problem is: above mentioned table is auto generated and I don't know how to do ToTable on it.
tried
modelBuilder.Entity().ToTable("client_users", t => t.ExcludeFromMigrations());
but it don't compile. modelBuilder.Entity() wants to have an object.
Please help
I added j.Metadata.SetIsTableExcludedFromMigrations(true); inside and it worked:
entity.HasMany(d => d.Users)
.WithMany(p => p.Clients)
...
j =>
{
...
j.Metadata.SetIsTableExcludedFromMigrations(true);
});

Load Related Data

I'm learning ASP.NET Core Web API and Entity Framework Core. Currently, I'm stuck figuring out how to populate the foreign keys with the actual values, as shown below.
Current Result:
Desired Result:
fkSecuritySecurityTypeId and fkSecurityExchangeId are populated.
DatabaseContext.cs:
The DatabaseContext class was built using dotnet ef dbcontext scaffold. Here's a portion of it:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Security>(entity =>
{
entity.HasOne(d => d.FkSecurityExchange)
.WithMany(p => p.Securities)
.HasForeignKey(d => d.FkSecurityExchangeId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.FkSecuritySecurityType)
.WithMany(p => p.Securities)
.HasForeignKey(d => d.FkSecuritySecurityTypeId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
Research:
AutoInclude() seems like the solution. I'm having a hard time understanding how to use AutoInclude() in my code since obviously my code is a bit different from how the docs use AutoInclude.
Questions:
Is AutoInclude() the correct approach ?
If so, how should it be used in this case ?
Thanks for your help.

Error upgrating to Entity Framework Core 3: RelationalReferenceCollectionBuilderExtensions does not exist in the current context

Im upgrating from Entity Framework Core 2 to Entity Framework Core 3. And I have this error:
Error CS0103 The name 'RelationalReferenceCollectionBuilderExtensions'
does not exist in the current context
The error is on method OnModelCreating(ModelBuilder modelBuilder), this is the code:
modelBuilder.Entity<Person>(entity =>
{
//some props
RelationalReferenceCollectionBuilderExtensions.HasConstraintName((ReferenceCollectionBuilder)entity
.HasOne(d => d.RuleCodeNavigation)
.WithMany(p => p.Person)
.HasForeignKey(d => d.RuleCode)
.OnDelete(DeleteBehavior.ClientSetNull), "FK_Person_Rules");
});
It seems the class RelationalReferenceCollectionBuilderExtensions does not exist in EF Core 3.
Any idea how I can fix this?
Not sure what happened to RelationalReferenceCollectionBuilderExtensions, but the suggested method to name your constraints is this
modelBuilder.Entity<Person>(entity =>
{
//some props
entity
.HasOne(d => d.RuleCodeNavigation)
.WithMany(p => p.Person)
.HasForeignKey(d => d.RuleCode)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Person_Rules");
});

How do I add a shadow property to an owned type?

Say I have a Customer entity with a list of owned types of Address. I also have an Office entity also with a list of owned types of Address.
In my OnModelCreating() method I have:
modelBuilder.Entity<Customer>().OwnsMany(s => s.Addresses, a =>
{
a.Property<DateTime>("CreatedDate");
a.Property<DateTime>("UpdatedDate");
}).ToTable("CustomerAddresses");
modelBuilder.Entity<Office>().OwnsMany(s => s.Addresses, a =>
{
a.Property<DateTime>("CreatedDate");
a.Property<DateTime>("UpdatedDate");
}).ToTable("OfficeAddresses");
I get an error of:
"Cannot use table 'Addresses' for entity type 'Customer.Addresses#Address' since it is being used for entity type 'Office.Addresses#Address' and there is no relationship between their primary keys.".
However, if I just have:
modelBuilder.Entity<Customer>().OwnsMany(s => s.Addresses).ToTable("CustomerAddresses");
modelBuilder.Entity<Office>().OwnsMany(s => s.Addresses).ToTable("OfficeAddresses");
it works.
So how do I add the shadow properties to this?
The solution if found is:
modelBuilder.Entity<Customer>().OwnsMany(s => s.Addresses, a =>
{
a.Property<DateTime>("CreatedDate");
a.Property<DateTime>("UpdatedDate");
a.ToTable("CustomerAddresses");
});
modelBuilder.Entity<Office>().OwnsMany(s => s.Addresses, a =>
{
a.Property<DateTime>("CreatedDate");
a.Property<DateTime>("UpdatedDate");
a.ToTable("OfficeAddresses");
});

Linq To Sql Entity Framework Getting Nested Entities

I'm trying to do an include of a nested entity. I assumed the below code would work but it does not recognize the CapitalMailOrders entitycollection. Can anyone point me in the right direction to include these?
var result = db.Contacts
.Include(a => a.IDXPageLinks)
.Include(b => b.ReboGatewayLoginInfoes)
.Include(c => c.SocialMedias)
.Include(d => d.WebSiteInfoes)
.Include(e => e.ContactImages)
.Include(f => f.RealtorSetUpProcesses)
.Include(h => h.RealtorSetUpProcesses.CapitalMailOrders) // getting compile time error here. Doesn't recognize Entity
.Include(g => g.Contact_CarrierCode_Assignments)
.FirstOrDefault(c => c.ContactID == id);
Thanks
The extra entity level is accessed from a collection and so you need to add a Select in order to bring all the entries into the include.
.Include(h => h.RealtorSetUpProcesses.Select(h2 => h2.CapitalMailOrders)