How to define two FK in the same table? - asp.net

I have a table called User which inherit the properties from IdentityUser, inside that table I added a reference to the UserFriendship table which need to store all the user friendship:
public class User : IdentityUser
{
public string FirstName { get; set; }
public DateTime BirthDate { get; set; }
public virtual ICollection<UserFriendship> UserFriendship { get; set; }
}
Essentially the UserFriendship contains two users, who are those who have a common friendship, this is the model definition:
public class UserFriendship
{
public int Id { get; set; }
[Key, ForeignKey("UserA")]
public string UserAId { get; set; }
public User UserA { get; set; }
[Key, ForeignKey("UserB")]
public string UserBId { get; set; }
public User UserB { get; set; }
[Required]
public DateTime DateTime { get; set; }
}
I defined the UserA and the UserB which are two FK of a User that are contained inside AspNetUsers table.
Now inside the FluentAPI I declared the following:
builder.Entity<UserFriendship>(entity =>
{
entity.HasKey(f => f.Id);
entity.HasOne(u => u.UserA)
.WithMany(n => n.UserFriendships)
.HasForeignKey(u => u.UserAId)
.IsRequired();
entity.HasOne(u => u.UserB)
.WithMany(n => n.UserFriendships)
.HasForeignKey(u => u.UserBId)
.IsRequired();
});
when I execute this command:
add-migration InitialMigration -context MyAppContext
I'll get:
Cannot create a relationship between 'User.UserFriendships' and 'UserFriendship.UserB', because there already is a relationship between 'User.UserFriendships' and 'UserFriendship.UserA'. Navigation properties can only participate in a single relationship.
I'm not an expert of EnityFramework, but based on that error I think that I cannot define two FK in the same table?
Sorry for any mistake, thanks.

You can define more than one FK in table.
The problem here is you are pointing two times to one navigation property - UserFriendships. The solution would be to create two navigation properties.
Navigation properties are used to browse the related data for specified foreign-key (you have one-to-many relationship) of entity.
Try this:
public class User
{
public string FirstName { get; set; }
public DateTime BirthDate { get; set; }
public ICollection<UserFriendship> UserAFriendships { get; set; }
public ICollection<UserFriendship> UserBFriendships { get; set; }
}
public class UserFriendship
{
public int Id { get; set; }
public string UserAId { get; set; }
public User UserA { get; set; }
public string UserBId { get; set; }
public User UserB { get; set; }
public DateTime DateTime { get; set; }
}
And define the relationship through fluent api as following:
modelBuilder.Entity<UserFriendship>(entity =>
{
entity.HasKey(f => f.Id);
entity.HasOne(u => u.UserA)
.WithMany(n => n.UserAFriendships)
.HasForeignKey(u => u.UserAId)
.IsRequired();
entity.HasOne(u => u.UserB)
.WithMany(n => n.UserBFriendships)
.HasForeignKey(u => u.UserBId)
.IsRequired();
});
What is more - you don't need to specify attributes Key, ForeignKey if you use Fluent API.

Related

Establishing one to one relations with Entity Framework 7

Having the following parent class:
[Table("smart_recharge_registro")]
public class SmartRechargeRegistro
{
[Key]
public int id { get; set; }
public SmartRechargeRequest request { get; set; }
public SmartRechargeProceso proceso { get; set; }
public SmartRechargeResponse response { get; set; }
}
Which in turn references the following child classes:
[Table("smart_recharge_request")]
public class SmartRechargeRequest
{
public String nombreDeUsuario { get; set; }
public String passwordDeUsuario { get; set; }
public String msisdnSuscriptor { get; set; }
}
and:
[Table("smart_recharge_proceso")]
public class SmartRechargeProceso
{
[Key]
public int id { get; set; }
public String carrierId { get; set; }
public String cliente { get; set; }
public String network { get; set; }
}
and lastly:
[Table("smart_recharge_response")]
public class SmartRechargeResponse
{
public Boolean responseSuccess { get; set; }
public int responseCode { get; set; }
public String? responseDetails { get; set; }
}
The Add-Migration and Update-Database command execute without problems. However, when I try to save
await _repository.RegistroColeccion.AddAsync(registro);
await _repositorio.SaveChangesAsync();
I get the following error:
Microsoft.EntityFrameworkCore.DbUpdateException: Could not save changes. Please configure your entity type accordingly.
---> MySql.Data.MySqlClient.MySqlException (0x80004005): Cannot add
or update a child row: a foreign key constraint fails
(beservicebroker_dev.registro_eventos_srdotnet, CONSTRAINT
FK_registro_eventos_srdotnet_SmartRechargeProceso_procesoid FOREIGN
KEY (procesoid) REFERENCES smartrechargeproceso (id) O)
To solve the problem, I tried to create one-to-one relationships following this tutorial
modelBuilder.Entity<SmartRechargeRegistro>()
.HasOne(s => s.request)
.WithOne(r => r.SmartRechargeRegistro)
.HasForeignKey<SmartRechargeRequest>(r => r.id);
modelBuilder.Entity<SmartRechargeRegistro>()
.HasOne(s => s.proceso)
.WithOne(p => p.SmartRechargeRegistro)
.HasForeignKey<SmartRechargeProceso>(p => p.id);
modelBuilder.Entity<SmartRechargeRegistro>()
.HasOne(s => s.response)
.WithOne(r => r.SmartRechargeRegistro)
.HasForeignKey<SmartRechargeResponse>(r => r.id);
Inside SmartRechargeRequest, SmartRechargeProceso and SmartRechargeResponse, added the following:
[JsonIgnore]
public SmartRechargeRegistro SmartRechargeRegistro { get; set; }
Also added inside SmartRechargeRequest and SmartRechargeResponse an id
[Key]
public int id { get; set; }
I'm still unable to test the endpoint because the SmartRechargeRequest and SmartRechargeResponse are completely disfigured in the swagger (even if the [JsonIgnore] or [IgnoreDataMember] annotations are set) due to the presence of that SmartRechargeRegistro object.
I'm pretty sure my solution is misguided and I'm getting the process completely wrong.
What would be the proper way to map one-to-one relationships for this case? Any help will be appreciated.
Please note that in reality, these classes are huge (dozens of properties), so it's not possible to merge all of them on a single table.

EFCore Many-To-Many relationship with the same table on the ends

I want to track referrals for users. There are two entities classes.
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public ICollection<Referral> Referrals { get; set; }
public ICollection<Referral> Referrees { get; set; }
}
public class Referral
{
public long ReferrerId { get; set; }
public long ReferreeId { get; set; }
public virtual User Referrer { get; set; }
public virtual User Referree { get; set; }
}
I defined relationships between them through fluent API on model creating (for the Referral entity)
builder.HasOne(r => r.Referrer).WithMany(u => u.Referrals).HasForeignKey(r => r.ReferrerId);
builder.HasOne(r => r.Referree).WithMany(u => u.Referrees).HasForeignKey(u => u.ReferreeId);
But when I try adding a migration, I get the
Unable to determine the relationship represented by navigation
property 'Referral.Referrer' of type 'User'. Either manually configure
the relationship, or ignore this property using the '[NotMapped]'
attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
error.
What am I doing wrong?

Introducing FOREIGN KEY constraint with ON DELETE NO ACTION doesn't working

I have 4 tables with between them foreign keys as:
Classification - Classification level - Classification value - Classification language
on add-migration it is ok, but when running update-database I get the error:
Introducing FOREIGN KEY constraint 'FK_dbClassificationValue_dbClassificationLevel_ClassificationLevelId' on table 'dbClassificationValue' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
The tables as mentioned in the error are defined as:
public class SuClassificationLevelModel
{
public int Id { get; set; }
public int ClassificationId { get; set; }
public int Sequence { get; set; }
public bool DateLevel { get; set; }
public bool OnTheFly { get; set; }
public bool Alphabetically { get; set; }
public bool CanLink { get; set; }
public bool InDropDown { get; set; }
public Guid CreatorId { get; set; }
public Guid ModifierId { get; set; }
public DateTime ModifiedDate { get; set; }
public DateTime CreatedDate { get; set; }
public virtual SuClassificationModel Classification { get; set; }
public virtual ICollection<SuClassificationLevelLanguageModel> ClassificationLevelLanguages { get; set; }
public virtual ICollection<SuClassificationValueModel> ClassificationValues { get; set; }
}
and
public class SuClassificationValueModel
{
public int Id { get; set; }
public int ClassificationLevelId { get; set; }
public int ParentValueId { get; set; }
public DateTimeOffset DateFrom { get; set; }
public DateTimeOffset DateTo { get; set; }
public virtual SuClassificationLevelModel ClassificationLevel { get; set; }
public virtual ICollection<SuClassificationValueLanguageModel> ClassificationValueLanguages { get; set; }
}
I have added the delete behavior line in my DBContect class as:
modelBuilder.Entity<SuClassificationValueModel>()
.HasOne(u => u.ClassificationLevel)
.WithMany(u => u.ClassificationValues)
.HasForeignKey(u => u.ClassificationLevelId)
.OnDelete(DeleteBehavior.Restrict);
Also, I have put this on the foreign keys between all tables of the cascading structure.
modelBuilder.Entity<SuClassificationLevelModel>()
.HasOne(u => u.Classification)
.WithMany(u => u.ClassificationLevels)
.HasForeignKey(u => u.ClassificationId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<SuClassificationValueModel>()
.HasOne(u => u.ClassificationLevel)
.WithMany(u => u.ClassificationValues)
.HasForeignKey(u => u.ClassificationLevelId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<SuClassificationValueLanguageModel>()
.HasOne(u => u.ClassificationValue)
.WithMany(u => u.ClassificationValueLanguages)
.HasForeignKey(u => u.ClassificationValueId)
.OnDelete(DeleteBehavior.Restrict);
Further, I have tried to set it for all foreign keys with:
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
As I don't need the cascading delete behavior.
After these different tries I did again an add-migration and update-database. But the error is still the same.
Any suggestions?
Finally, I went into the migration files and changed everywhere from cascade to restrict. As I don't want to use cascade anyway. And now it works.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

I am getting these errors when trying to create a merchant.
FlavorPing.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
FlavorPing.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
UserLogins: EntityType: EntitySet 'UserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
UserRoles: EntityType: EntitySet 'UserRoles' is based on type 'IdentityUserRole' that has no keys defined."
Here is my merchant model:
namespace FlavorPing.Models
{
public class Merchant
{
//Meant to inherit identity.
//[ForeignKey("ApplicationUserId")]
public string ApplicationUserId { get; set; }
[ForeignKey("ApplicationUser")]
public virtual List<ApplicationUser> ApplicationUser { get; set; }
[Key]
public int MerchantID { get; set; }
[Required]
[Display(Name = "Business Name")]
public string MerchantName { get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string email { get; set; }
//need to create formatting here.
[Required]
[Display(Name = "Web Site Link")]
public string website { get; set; }
//public int MenuItemID { get; set; }
public virtual List<MenuItem> MenuItems { get; set; }
public virtual MerchantDetails MerchantDetails { get; set; }
public ICollection<FollowerMenuItemMerchant> FollowerMenuItemMerchants { get; set; }
}
}
Here is the create controller for merchant, which is where I am getting the error:
// POST: Merchants/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MerchantID,MerchantName,email,website")] Merchant merchant)
{
if (ModelState.IsValid)
{
merchant.ApplicationUserId = User.Identity.GetUserId();
db.Merchants.Add(merchant);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(merchant);
}
Here is my DBContext:
namespace FlavorPing.Models
{
public class FlavorPingContext : IdentityDbContext
{
public FlavorPingContext()
: base("name=FlavorPingContext")
{
}
public System.Data.Entity.DbSet<FlavorPing.Models.Merchant> Merchants { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.MenuItem> MenuItems { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.MerchantDetails> MerchantDetails { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.Follower> Followers { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.FollowerMenuItemMerchant> FollowerMenuItemMerchants { get; set; }
public DbSet<IdentityUserLogin> UserLogins { get; set; }
public DbSet<IdentityUserClaim> UserClaims { get; set; }
public DbSet<IdentityUserRole> UserRoles { get; set; }
protected override void OnModelCreating(DbModelBuilder builder)
{
// Primary keys
builder.Entity<Follower>().HasKey(q => q.FollowerID);
builder.Entity<MenuItem>().HasKey(q => q.MenuItemID);
builder.Entity<Merchant>().HasKey(q => q.MerchantID);
builder.Entity<FollowerMenuItemMerchant>().HasKey(q =>
new
{
q.FollowerID,
q.MenuItemID,
q.MerchantID
});
// Relationships
builder.Entity<FollowerMenuItemMerchant>()
.HasRequired(t => t.Follower)
.WithMany(t => t.FollowerMenuItemMerchants)
.HasForeignKey(t => t.FollowerID);
builder.Entity<FollowerMenuItemMerchant>()
.HasRequired(t => t.MenuItem)
.WithMany(t => t.FollowerMenuItemMerchants)
.HasForeignKey(t => t.MenuItemID);
builder.Entity<FollowerMenuItemMerchant>()
.HasRequired(t => t.Merchant)
.WithMany(t => t.FollowerMenuItemMerchants)
.HasForeignKey(t => t.MerchantID);
builder.Conventions.Remove<PluralizingTableNameConvention>();
builder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
}
I am trying to follow the example (option2) in this link: EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType
I am trying Option 2 because I want to avoid having two DB's. But I am new to managing a DB so if you think I should do Option 3 please advise as to why, or if you see why I am getting this error please tell me why. Thanks in advance!
Ok I fixed my issue by adding this into my DBContext class.
builder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
builder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
builder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
I think you get the errors because your foreign key attributes aren't in the correct spot (and have the wrong name), instead of this:
public string ApplicationUserId { get; set; }
[ForeignKey("ApplicationUser")]
public virtual List<ApplicationUser> ApplicationUser { get; set; }
You need to do this:
[ForeignKey("ApplicationUser")]
public string ApplicationUserId { get; set; }
public virtual List<ApplicationUser> ApplicationUser { get; set; }
The ID is the foreign key to the virtual entity, not the other way around.

Code-first database mapping, table missing (wasn't created) for many-to-many relationship

I am building ASP.NET webforms application using Entity Framework 6.1, with code-first approach to generate database. I have two tables, Product and Tags, in many-to-many relationship. Classes are below:
public class Product
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products{ get; set; }
}
I want two junction tables out of this relationship ProductTags and ProductTagsTradeFor. So I overrided OnModelCreating of WebsiteDbContext.
modelBuilder.Entity<Product>().HasMany<Tag>(s => s.Tags).WithMany(c => c.Products)
.Map(cs =>
{
cs.MapLeftKey("ProductId");
cs.MapRightKey("TagId");
cs.ToTable("ProductTags");
});
modelBuilder.Entity<Product>().HasMany<Tag>(s => s.Tags).WithMany(c => c.Products)
.Map(cs =>
{
cs.MapLeftKey("ProductId");
cs.MapRightKey("TagId");
cs.ToTable("ProductTradeForTags");
});
After running the application, database was created and table ProductTradeForTags is present but table ProductTags was missing.
What is the problem and how do I fix it so both tables are created?
You can't share the navigation properties. You will need to add a second set of navigation collections to each:
public class Product
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Tag> TradeForTags { get; set; }
}
public class Tag
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products{ get; set; }
public virtual ICollection<Product> TradeForProducts{ get; set; }
}
Then
modelBuilder.Entity<Product>().HasMany(s => s.Tags).WithMany(c => c.Products)
.Map(cs =>
{
cs.MapLeftKey("ProductId");
cs.MapRightKey("TagId");
cs.ToTable("ProductTags");
});
modelBuilder.Entity<Product>().HasMany(s => s.TradeForTags).WithMany(c => c.TradeForProducts)
.Map(cs =>
{
cs.MapLeftKey("ProductId");
cs.MapRightKey("TagId");
cs.ToTable("ProductTradeForTags");
});
Your model require to navigate from a Tag to Products and from a Product to Tags.
In this case one association table is enough.
EF should raise an exception but it simply ignores the first configuration.

Resources