EF Core one-to-many relationship with multiple contexts (databases) - asp.net

I have contexts with entities like this:
public class CompanyContext : DbContext
{
public DbSet<StoreModel> Stores { get; set; }
// Other entities
}
public class DepartmentContext : DbContext
{
public DbSet<OrderModel> Orders { get; set; }
// Other entities
}
public class StoreModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<OrderModel> ReceivedOrders { get; set; }
public virtual ICollection<OrderModel> PreparedOrders { get; set; }
public virtual ICollection<OrderModel> IssuedOrders { get; set; }
}
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public StoreModel GettingStore { get; set; }
public StoreModel PreparingStore { get; set; }
public StoreModel IssuanceStore { get; set; }
}
For example a user makes an order in storeA, but wants to receive it in storeC, and it order will preparing in storeB. And I needs a statiscics about store received/prepared/issued orders.
When I try to create a migrations, EF throws exceptions "Unable to determine the relationship represented by navigation 'OrderModel.GettingStore' of type 'StoreModel'" and "Unable to determine the relationship represented by navigation 'StoreModel.IssuedOrders' of type 'ICollection<OrderModel>'". If I understand correctly, this happens because entities are defined in different contexts.
Now I just use next model:
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public Guid GettingStoreId { get; set; }
public Guid PreparingStoreId { get; set; }
public Guid IssuanceStoreId { get; set; }
}
This works fine, but perhaps there are options that allow to create such a structure using navigation properties, with correct relationships between these entities from different contexts(databases).

First, the map of a different database was not placed in tables of different application formats, so think that you have a domain that should be well defined in your application, that way you would have the mapping of your application like this:
public class DomainNameContext: DbContext
{
public DomainNameContext(): base()
{
}
public DbSet<StoreModel> Stores { get; set; }
public DbSet<OrderModel> Orders { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// config mapping methods
}
}
another thing, the relation you are using doesn't work so you can't have a repetition of Orders within the same class because this is not one -> many, this statement means that a StoreModel line can have many lines in the OrderModel this way would be like this
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public Guid StoreModeId { get; set; } // this part will show the entity framework that this is the fk it will correlate
public StoreModel StoreModel { get; set; }
}
public class StoreModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<OrderModel> OrderModels { get; set; }
}
see that if you are wanting to have many StoreModel related to many OrderModel then you need to use many -> many which microsoft documentation foresees to use as well
good to map this within its context it is necessary in OnModelCreating to use its mapping like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// config mapping methods
modelBuilder.Entity<StoreModel>()
.HasMany<OrderModel>(g => g.OrderModels )
.HasForeignkey<Guid>(s => s.StoreModeId )
}
you can have a look at the microsoft documentation enter link description here, enter link description here
now if you need to map between contexts you will have to use dapper to make separate queries in separate bases the entity has support for that in this link enter link description here
and then you can make the necessary inner joins so that you can use it but natively this does not exist, I advise you to rethink your database so that it can make more sense to a relational model, perhaps putting types for your StoreModel and OrderModel so you can use the way I wanted the types GettingStore, PreparingStore, IssuanceStore using an enum for this to make it explicit

Related

Introducing FOREIGN KEY constraint on table may cause cycles or multiple cascade paths even after removing the affected field completely

I'm quite new to .net and entity framework (this is my first project) and I'm getting the following error when trying to update the database:
*Introducing FOREIGN KEY constraint 'FK_Rating_User_UserId' on table 'Rating' 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.*
I tried doing what it says (at least I think so) by adding the following to my dbContext class:
protected override void OnModelCreating(ModelBuilder modelbuilder)
{
modelbuilder.Entity<Rating>().HasOne(u => u.User).WithMany().OnDelete(DeleteBehavior.Restrict);
modelbuilder.Entity<Rating>().HasOne(g => g.Game).WithMany().OnDelete(DeleteBehavior.Restrict);
}
Not sure have I formulated that method correctly but it did not help (I tried with different DeleteBehavior like SetNull and NoAction)
The thing that really got me confused is that the issue appears even after removing all fields related to other tables from Rating class or even all references between all classes.
My Rating class:
public class Rating
{
public long RatingId { get; set; }
//[Rating]
public virtual Game Game { get; set; } // issue appears even after removing this and User line
//[Rating]
public int Score { get; set; }
public string CommentTitle { get; set; }
public string CommentDescription { get; set; }
//[Rating]
public virtual User User { get; set; }// issue appears even after removing this and Game line
}
User class:
public class User
{
public long UserId { get; set; }
//[Required]
public bool IsModerator { get; set; }
//[Required]
public string Username { get; set; }
//[Required]
public string Email { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
//[Required]
public string Password { get; set; }
//[Required]
public string Salt { get; set; }
public string Description { get; set; }
}
Game class:
public class Game
{
public long GameId { get; set; }
//[Required]
public virtual User User { get; set; }
//[Required]
public string Title { get; set; }
public string Description { get; set; }
//[Required]
public string PricingType { get; set; }
public float MinDonation { get; set; }
public float MaxDonation { get; set; }
//[Required]
public string FileLocation { get; set; }
public float AverageRaiting { get; set; }
public int DownloadCount { get; set; }
}
GameImage class (probably unrelated to the issue just wanted to give a full context)
public class GameImage
{
public long GameImageId { get; set; }
//[Required]
public virtual Game Game { get; set; }
//[Required]
public string Location { get; set; }
//[Required]
public bool IsThumbnail { get; set; }
}
dbContext class:
public class dbContext : DbContext
{
public dbContext(DbContextOptions<dbContext> options) : base(options)
{
}
public DbSet<User> User { get; set; }
public DbSet<Rating> Rating { get; set; }
public DbSet<GameImage> GameImage { get; set; }
public DbSet<Game> Game { get; set; }
}
The issue only appeared after I tried to update the database. The first few migrations and updates were ok, however, then I tried adding [Required] annotation (you can see them commented in the above code) as I noticed that most of the fields were created as nullable in my database - after that the issue starting to occur even after removing the annotations.
In case that matters, I'm using Visual Studio 2019 and SQL Server Express
Does anyone have any idea what may be the cause of this?
Edit:
Image of of my database schema diagram from SSMS
As you can see in the database schema it's visible that there are indeed cycles in the database, however, I cannot get rid of them as Entity Framework's command "Update-Database" does not update the DB and just throws the error mentioned above.
Based on my test, you can try the following steps to solve the problem.
First, please change your dbcontext class into the following code.
public class dbContext : DbContext
{
public dbContext() : base("name=MyContext") { }
public DbSet<User> User { get; set; }
public DbSet<Rating> Rating { get; set; }
public DbSet<GameImage> GameImage { get; set; }
public DbSet<Game> Game { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
Second, please delete all the tables the database.
Third, please try the following command in your package console.
PM> Update-Database -Force
Finally, you can see the new tables in the databse.

Creating navigation code-first results in the error: does not declare a navigation property with the name

query.Include("Store_Location").Load();
throws:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: A specified Include path is not valid. The EntityType 'Model.Order' does not declare a navigation property with the name 'Store_Location'.
I used the following code in order to create the navigation code-first:
public partial class Order
{
public Nullable<int> Store_Location_ID { get; set; }
public virtual Store_Location Store_Location { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
public partial class Store_Location
{
public int ID { get; set; }
public virtual ICollection<Order> Orders { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
https://learn.microsoft.com/en-us/ef/ef6/fundamentals/relationships
Do I need to use the designer? Is there anything I need to do in order for the navigation to be created?
If you create your database with code first approach, then your entities should not be partial classes. Define them like this:
public class Order
{
public int? StoreLocationId { get; set; }
public virtual StoreLocation StoreLocation { get; set; }
}
public class StoreLocation
{
public int Id { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
Then you should create a DbContext class:
public class StoreDbContext : DbContext
{
public StoreDbContext(DbContextOptions<StoreDbContext> options) : base(options)
{
}
public virtual DbSet<StoreLocation> StoreLocations { get; set; }
public virtual DbSet<Order> Orders { get; set; }
}
After creating a context you can use the ef commands to create your database. You can read more about ef core here: https://learn.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli
If you define your classes like I did above, you can include your navigation properties strongly typed like this:
query.Include(order => order.StoreLocation);

Entity Framework shows inconsistent behaviour when used with Asp.net Identity

I have 3 tables Violation,Comment and and auto generated AspNetUsers respectively.The relationship between them as follows.
I am using code-first approach and my models are as follows.Some properties are removed for brevity.
Violation Model
public class Violation
{
public Violation()
{
this.Comments = new HashSet<Comment>();
}
public int Id { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ApplicationUser CreatorUser { get; set; }
}
Comment Model
public class Comment
{
public int Id { get; set; }
[Required]
public string Content { get; set; }
[Required]
public DateTime PostedDateTime { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public Violation Violation { get; set; }
}
ApplicationUser(AspNetUsers Table)
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
this.Comments = new List<Comment>();
this.Violations = new List<Violation>();
}
public virtual List<Comment> Comments { get; set; }
public virtual List<Violation> Violations { get; set; }
}
The problem is that when I try to retrieve Comment's ApplicationUser navigation property , I see many of them pointing to a null property even database has proper record for each of them.
Shortly,EF doesn't retrieve database records properly.I stuck with it,can't find the reason.
In fact, it's not being lazy-loaded. You didn't add the virtual keyword to your Comment.ApplicationUser property, so Entity Framework cannot override it to add the lazy-loading logic. As a result, it's always going to be null unless you explicitly load it. Add the virtual keyword, and you'll be fine.
If you want the navigation properties populated you need to include them in the query:
var comments = context.Comments
.Include(c => c.Violation)
.Include(c => c.ApplicationUser)
.Where(x => x.Violation.Id == violationId);
https://msdn.microsoft.com/en-us/data/jj574232.aspx#eager

Create Dapper Repository Method for Complex Data

I want to create a generic repository method for the complex data(Data Result of multiple joins in database). Following are the classes which hold the data . The data comes from SQL is the join of three tables(Tables architecture is same as of class)
public class InterfaceHeaderSetting
{
public Guid Id { get; set; }
public string CodaDocCode { get; set; }
public string Company { get; set; }
public string Currency { get; set; }
public string DocDescription { get; set; }
public Screen Screen { get; set; }
public Interface Interface { get; set; }
}
public class Screen
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Interface
{
public Guid Id { get; set; }
public string Name { get; set; }
}
I have the repository methods like
public IEnumerable<T> GetAllDynamic(string sql)
{
return Connection.Query<T>(sql, commandType: CommandType.StoredProcedure).ToList();
}
public T Update(T entity, string sql, object dynamicParameters)
{
return
Connection.Query<T>(sql, dynamicParameters, commandType: CommandType.StoredProcedure).SingleOrDefault();
}
I want one more repository method by which I can fill the objects like InterfaceHeaderSetting object.
I don't think you should reinvent the wheel. For this type of function i think Entity Framework is the solution.
In my projects i let entity framework handle more advanced querys that need joins and let dapper do the simple insert, update and select jobs.

Handling default values for models in EF4

I'm wondering what's the best way to handle default values for relationships when making models. (Specifically EF4)
For example, my Organization has a default Contact and I was wondering which one was the best approach. I got these two options (or any other anyone suggests if better)
Using Relationship:
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
}
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Contact> Contacts { get; set; }
//Use a relationship for the default contact?
public Contact DefaultContact { get; set; }
}
Using Value:
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
//Use value?
public boolean IsDefault { get; set; }
}
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Contact> Contacts { get; set; }
}
I'd go with Option 1. While 2 is definitely easier to implement, it doesn't enforce rules such as "There cannot be 2 default contacts". I end up with something like the following:
public class Organization {
// ...
public virtual ICollection<Contact> { get;set; }
[ForeignKey("DefaultContactId")]
public Contact DefaultContact { get;set; }
public int? DefaultContactId { get;set; }
}
There's a limitation of this approach - it doesn't work nested deletes (see this question for more details). Because of this, you need to disable CascadeOnDelete for the 1-to-many relationship:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>().HasRequired(co => co.Organization).WithMany().WillCascadeOnDelete(false);
}
(Code done without testing, but should work)
The other problem with this is that it's not possible to add the Default Contact at the same time as you're adding the organization, as EF can't figure out the correct order of statements. You need to call .SaveChanges between each. You can still use a TransactionScope to overcome this, but it's not clean:
using (var ts = new TransactionScope())
{
Organization org = new Organization
{
// ...
Contacts = new Collection<Contact>()
}
org.Contacts = new Contact() {};
orgRepo.SaveChanges();
// Now wire up the default contact
org.DefaultContact = org.Contacts.First();
orgRepo.SaveChanges();
}

Resources