I am working on a messenger API, and it goning be something like discord which someone sends a friend request to another user, and if the user accepted, they start messaging. as you know each FriendRequest has two contacts, sender and receiver, there are two ways to implement this relationship, one way is to define a many-to-many relationship between FriendRequest and contact and limit the FriendRequest's contacts to two. the other way is to define two properties in FriendRequest, SenderContact and ReceiverContact.
I chose the second way which each FriendRequest should have two foreign keys with two contacts. But EF added another foreign key automatically.
I just want to know two things
1: Is the second way that I chose a good way? Is there any better way to implement this situation?
2: Can I prevent EF from creating the ContactId column?
OnModelCreating in MyConext:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Contact>().HasMany<FriendRequest>().WithOne(f => f.FromContact);
builder.Entity<Contact>().HasMany<FriendRequest>().WithOne(f => f.ToContact);
base.OnModelCreating(builder);
}
FriendRequest:
public class FriendRequest
{
public int Id { get; set; }
public Contact FromContact { get; set; }
public Contact ToContact { get; set; }
public string Text { get; set; }
}
Contact:
public class Contact
{
[Key]
public int Id { get; set; }
public int UserId { get; set; }
public string Username { get; set; }
public ICollection<Chat> Chats { get; set; }
public ICollection<FriendRequest> FriendRequests { get; set; }
public ICollection<Contact> Friends { get; set; }
}
Your approach seems okay to me, but you have a configuration error.
Your contact object should be
public class Contact
{
[Key]
public int Id { get; set; }
public int UserId { get; set; }
public string Username { get; set; }
public ICollection<Chat> Chats { get; set; }
public ICollection<FriendRequest> SentFriendRequests { get; set; }
public ICollection<FriendRequest> ReceivedFriendRequests { get; set; }
public ICollection<Contact> Friends { get; set; }
}
FriendRequest can stay the same, tho it is recommended to define a foreign key
public class FriendRequest
{
public int Id { get; set; }
public Contact FromContact { get; set; }
public Contact ToContact { get; set; }
public string Text { get; set; }
}
And the configuration
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Contact>()
.HasMany<FriendRequest>(c => c.SentFriendRequests)
.WithOne(f => f.FromContact);
builder.Entity<Contact>()
.HasMany<FriendRequest>(c => c.ReceivedFriendRequests)
.WithOne(f => f.ToContact);
base.OnModelCreating(builder);
}
I always take a second look at the MS documentation when configuring relations, I recommend you do that.
Related
I'm trying to make an insert in a SQL database using Entity Framework 6 and I'm stuck on this issue that I cannot solve.
The error that I keep getting is :
UpdateException: Entities in 'Connect.CompanyFinancialDetails' participate in the 'Company_CompanyFinancialDetails' relationship. 0 related 'Company_CompanyFinancialDetails_Source' were found. 1 'Company_CompanyFinancialDetails_Source' is expected
I have these 2 entities:
public class Company
{
public long CUI { get; set; }
public string UserName { get; set; }
public string CompanyName { get; set; }
public string Symbol { get; set; }
public int? SharesCount { get; set; }
public decimal? SharePrice { get; set; }
public virtual Account Account { get; set; }
public virtual CompanyFinancialDetails CompanyFinancialDetails { get; set; }
}
public class CompanyFinancialDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
// other properties
public decimal? NumberOfEmployees { get; set; }
public virtual Company Company { get; set; }
}
This is the Fluent API configuration:
public DbSet<Account> SignUpModels { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<CompanyFinancialDetails> CompanyFinancialDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>()
.HasKey(k => k.Id)
.HasOptional(s => s.Company)
.WithRequired(d => d.Account);
modelBuilder.Entity<Company>()
.HasKey(k => k.CUI)
.HasOptional(s => s.CompanyFinancialDetails)
.WithRequired(d => d.Company);
}
The relationship that I want to have is 1-many (one Company has many CompanyFinancialDetails).
This is the code where I add the objects to the database:
Company co = Context.Find(username);
foreach (CompanyFinancialDetails s in c)
{
s.Company = co;
}
a.CompanyFinancialDetails.AddRange(c);
a.SaveChanges();
I get a list of CompanyFinancialDetails and I add them using the AddRange method. I had this issue before and what I did was to add the virtual property object to the object that I wanted to insert in the database and it worked. This is what I tried to do here: the Find() method gets the company object that is related to the CompanyFinancialDetails and for each CompanyFinancialDetails object an Company virtual property is adding the related company object.
Well, it didn't work, when the SaveChanges() method is called, I get that error. Any help would be appreciated.
One company can have many addresses, however each company has a main address.
I am looking to find the best way to create this kind of relation in EF Core.
Below is what I came up with. Is there a better way? Am I way off entirely?
Models
public class Company
{
public int Id { get; set; }
public int MainAddressId { get; set; }
public Address MainAddress { get; set; }
public ICollection<CompanyAddress> CompanyAddresses { get; set; }
// other company info
}
public class Address
{
public int Id { get; set; }
public int CompanyAddressId { get; set; }
public CompanyAddress CompanyAddress { get; set; }
// other address info
}
public class CompanyAddress
{
public int CompanyId { get; set; }
public Company Company { get; set; }
public int AddressId { get; set; }
public Address Address { get; set; }
public bool IsMain { get; set; }
}
DataContext.cs
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Company> Companies { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<CompanyAddress> CompanyAddresses { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<CompanyAddress>()
.HasKey(ca => new {ca.CompanyId, ca.AddressId});
builder.Entity<CompanyAddress>()
.HasOne(ca => ca.Company)
.WithMany(ca => ca.CompanyAddresses)
.HasForeignKey(ca => ca.CompanyId)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<CompanyAddress>()
.HasOne(ca => ca.Address)
.WithOne(ca => ca.CompanyAddresses)
.HasForeignKey(ca => ca.AddressId)
.OnDelete(DeleteBehavior.Cascade);
}
}
In my opinion, dead on. There are always other ways. But this is straight-forward and easily understood. MainAddress and MainAddressId are redundant. You don't have lazy loading (virtual) so you can easily determine the main address by
dbContext.Companies.FirstOrDefault(p => p.Id = <myCompanyId>);
dbContext.CompanyAddresses.FirstOrDefault(p => p.CompanyId == <myCompanyId> && p.IsMain);
If you go with lazy loading later, just add .Include("Address") to the second query. And yes, you can combine the two.
Hi I have problem with EF Core insert entity. The problem is that I need to insert new entity with relation to another one which is already existing. I have created the relations with fluent API. I have done this for two times. First I am creating car and adding the last edited by field with Identity user and all works but when I am trying to do the same with another entity it crashes down with
My fluent APi code which works good:
builder.Entity<Car>()
.HasOne(x => x.Owner)
.WithMany(x => x.OwnerCars)
.HasForeignKey(x => x.OwnerId);
Here is car entity:
public class Car : CarBase
{
[Key]
public int CarId { get; set; }
public bool IsTrailer { get; set; }
public virtual TrailerType TrailerType { get; set; }
public virtual int? TrailerTypeId { get; set; }
public virtual ApplicationUser Owner { get; set; }
public virtual string OwnerId { get; set; }
}
and here is Application user entity
public class ApplicationUser : IdentityUser
{
[MaxLength(100)]
public string Address { get; set; }
public DateTime CreatedDateTime { get; set; }
public DateTime LastEditationDateTime { get; set; }
public virtual ApplicationUser LastEditedBy { get; set; }
public bool IsDeleted { get; set; }
public virtual DateTime DeletedDateTime { get; set; }
public ICollection<DriverLicenseApplicationUser> DriverLicenses { get; set; }
public ICollection<RideApplicationUser> Rides { get; set; }
public ICollection<Car> OwnerCars { get; set; }
public ICollection<Car> EditedCars { get; set; }
public ICollection<Trailer> EditedTrailers { get; set; }
public ICollection<Customer> EditedCustomers { get; set; }
}
To add this entity I only call this function and all works.
public Car CreateCar(Car car)
{
_context.Cars.Add(car);
return car;
}
But when I want to save this way this another entity type it shows an error. All steps are same so I do not understand this. Here I am adding the code I use to do that.
builder.Entity<Trailer>()
.HasOne(x => x.TrailerType)
.WithMany(x => x.Trailers)
.HasForeignKey(x => x.TrailerTypeId);
Here is Trailer:
public class Trailer : CarBase
{
[Key]
public int TrailerId { get; set; }
//[Required]
public virtual TrailerType TrailerType { get; set; }
public virtual int TrailerTypeId { get; set; }
}
and here is traylerTyper:
public class TrailerType:Trackable
{
//[Key]
public int TrailerTypeId { get; set; }
[MaxLength(100)]
[Required]
public string Type { get; set; }
public string Note { get; set; }
public ICollection<Car> TrailerTypeCars { get; set; }
public ICollection<Trailer> Trailers{ get; set; }
}
and the method is the same as the one already mentioned
public Trailer CreateTrailer(Trailer trailer)
{
trailer.TrailerTypeId = trailer.TrailerType.TrailerTypeId;
//_context.Attach(trailer.TrailerType);
var result = _context.Trailers.Add(trailer);
return result.Entity;
}
When I uncomment the attach it works but I think that I dont have to attach this because I have got the relation based on IDs and the example mentioned first works great. It gives me no sense. So if anyone could give me advice it would be awsome.
Here is the error I am getting:
Cannot insert explicit value for identity column in table 'TrailerTypes' when IDENTITY_INSERT is set to OFF.
It looks like the EF doesnt know that the traylertype entity already exists and is trying to insert the same entity again and the app crashes because it already exists and I am not allowing to insert IDs directly. As I said I have absolutely no idea why is this happening.
The problem is Lazy loading. Propetry from ViewModel is not completly same as property in Database and EF tracks whole graph of property in object and doesn´t recognize that it is the same object. The solution is to work only with IDs instead with whole objects.
I have a relatively complex relationship I need to set up between a User object and a lot of lookup tables. The user object is your run of the mill user model:
public class Youth : IAuditInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public Guid YouthGuid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string ImageName { get; set; }
[ForeignKey("FkYouthId")]
public ICollection<User> Parents { get; set; }
public CubPack Pack { get; set; }
public virtual ICollection<RequirementsLog> RequirementsLogs { get; set; }
public Youth()
{
Parents = new List<User>();
}
}
The lookup tables is where it gets complex and I can't figure out the path of least complexity in binding them together. For the lookups it is a series of tables starting with one 'master' table, that rolls down hierarchically to requirements and sub requirements, like this:
Master:
public class BearTrail
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<BearTrailRequiredBadge> BearTrailRequiredBadges { get; set; }
public virtual ICollection<BearTrailElectiveBadge> BearTrailElectivedBadges { get; set; }
}
Required Badges:
public class BearTrailRequiredBadge
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public string Description { get; set; }
public virtual ICollection<BearTrailRequiredBadgeSubRequirement> BearTrailRequiredBadgeSubRequirements { get; set; }
}
Required Badge sub requirement:
public class BearTrailRequiredBadgeSubRequirement
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Number { get; set; }
public string Text { get; set; }
public bool Required { get; set; }
}
This is one set of the lookups, there are about four nested classes like this, and some one off tables as well. Total lookup tables is about 16, give or take.
I was initially thinking if using my RequirementLog model to bind it:
public class RequirementsLog
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual ICollection<Youth> Youth { get; set; }
public BearTrail BearTrailRequirements { get; set; }
public TigerTrail TigerTrailRequirements { get; set; }
public WolfTrail WolfTrailRequirements { get; set; }
public WebelosTrail WebelosTrailRequirements { get; set; }
public WebelosArrowOfLight WebelosArrowOfLightRequirements { get; set; }
}
So there is a many to many between RequirementsLog and Youth. The table created out of RequirementsLog has one PK column (ID), and FK columns for each property. The many to many table created out of this (RequirementsLogYouths) has two PKs (RequirementsLogId, and YouthId).
Am I going about this the right way? The end goal is to have the 16 or so tables server as just lists of various requirements, and have another table(s) to track a particular youths progress through the requirements. I have a hard time visualizes some of this DBA stuff, so any input would be greatly appreciated.
In most cases, a requirements "log" be in a one (people) to many (the log).
Unless... One logged item is for many kids...
If so, the you need a third table, that maps many people to multiple logged events. That is, if this is truly a many to many. In general, that situation almost always begs for a third, intermediate mapping table. Read up a bit on many to many designs, and you'll quickly see it, and how simple it is.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Entity1>()
.HasMany(b => b.Entities2)
.WithMany(p => p.Entities1)
.Map(m =>
{
m.ToTable("Entitie1Entity2");
m.MapLeftKey("Entity1Id");
m.MapRightKey("Entity2Id");
});
}
I can't update navigation property
I have two entities: User
public class User : Entity
{
public string Username { get; set; }
public string Password { get; set; }
public int? AddressId { get; set; }
public virtual Address Address { get; set; }
}
And Address
public class Address : Entity
{
public string AddressName { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
When i am trying to do following:
address.User = user;
address userId updates succesfully, and in commit method, entity state is Modified.
But users AddressId won't update.
Here is my context
public DbSet<User> Users { get; set; }
public DbSet<Address> Addresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(x=>x.Address)
.WithMany()
.HasForeignKey(x=>x.AddressId)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
And i am using unity framework and genereic repository pattern.
I tried to set all properties to virtual but no effect.
I think there is a conception problem here, beyond your foreign key problem.
Why do you refer an AddressId if you have already an Address object in your User class ? It's the same thing for your Address class.
Maybe you should try something like this :
public class User : Entity
{
public string Username { get; set; }
public string Password { get; set; }
public virtual Address Address { get; set; }
}
public class Address : Entity
{
public string AddressName { get; set; }
public virtual User User { get; set; }
}
But just to make it clear, Entity Framework is not a magic wizard (clause to...). With your architecture, you have to manually update BOTH foreign keys (if you want to keep your AddressId and UserId properties).