Relationship one to many in EF - asp.net-web-api

I have the following problem: it turns out that when I write the controller of my article table from my database, I get an error on my web page. I'm using ASP.NET Core 5 with a pre-existing database. I'm a newbie at this, I'm learning by creating projects.
In my controller class I have this:
https://codeshare.io/3AoPBB
I have this class articlesviewmodel:
https://codeshare.io/mp08vk
And this is my articlemap:
https://codeshare.io/0gQqZv
DbContextSytem: https://codeshare.io/1YD6Bj
Article table in SQL Server database:
https://codeshare.io/DZrPJk
Class Category for a table in SQL Server:
public class Category
{
public int idcategory { get; set; }
[Required]
[StringLength(50, MinimumLength = 3, ErrorMessage = "The Category must not have more than 50 characters")]
public string namecategory { get; set; }
public string descategory { get; set; }
public bool numberstatate { get; set; }
// modify table category
public ICollection<Article> articles { get; set; }
}
I really don't know what I can be doing wrong in the include

I solved it in the following way, it turns out that I got an error because the foreign key was missing between the category and articles tables, I solved it with the following line of code in the dbcontextsystem under modelBuilder.ApplyConfiguration(new ArticleMap());
modelBuilder.Entity<Article>().HasOne(a => a.Category).WithMany(c => c.articles).HasForeignKey(a => a.idcategory);

Related

Entity Framework, two Many to Many relationship to same object using Fluent API

I am trying to define two many to many relationship to same object using fluent api.
Here is the simplified model:
public class PurchaseRequisition
{
[Key, ForeignKey("Transaction")]
public int TransactionId { get; set; }
public virtual ICollection<People> RequisitionedBys { get; set; }
public virtual ICollection<People> AuthorizedSignatures { get; set; }
}
public class People
{
[Key]
public string Id{ get; set; }
public string FullName { get; set; }
public virtual ICollection<PurchaseRequisition> PurchaseRequisitionsForRequisitionedBys { get; set; }
public virtual ICollection<PurchaseRequisition> PurchaseRequisitionsForAuthorizedSignatures { get; set; }
}
Here is the fluent api code:
modelBuilder.Entity<PurchaseRequisition>()
.HasMany(a => a.RequisitionedBys)
.WithMany(b => b.PurchaseRequisitionsForRequisitionedBys)
.Map(x =>
{
x.MapLeftKey("PurchaseRequisitionId");
x.MapRightKey("RequisitionedById");
x.ToTable("PurchaseRequisitionRequisitionedBy");
});
modelBuilder.Entity<PurchaseRequisition>()
.HasMany(a => a.AuthorizedSignatures)
.WithMany(b =>b.PurchaseRequisitionsForAuthorizedSignatures)
.Map(x =>
{
x.MapLeftKey("PurchaseRequisitionId");
x.MapRightKey("AuthorizedSignatureId");
x.ToTable("PurchaseRequisitionAuthorizedSignature");
});
What I want is to generate two separate linking tables, but what EF generates is two foreign key columns to PurchaseRequisition in People table and 1 foreign key column to People in PurchaseRequisition field.
Can anyone tell me what might be wrong?
The problem was fixed.
I mistakenly thought that my database initializer code would drop and recreate the database since I made changes to the model classes and my Initializer class extended DropCreateDatabaseIfModelChanges.
As Slauma suggested, fluent api code was not being reached even though the model has been changed. I was setting the initializer using SetInitializer() method and this code only ran when I used a context instance for the first time to access the DB.

EF 4.1 Code First Relationship table

Setup
Using MVC 3 + Code First
Here are my classes
public class Member
{
[Key]
public Guid ID { get; set; }
[Required]
public String Email { get; set; }
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
public String Sex { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public DateTime RegisterDate { get; set; }
public DateTime LastOnline { get; set; }
public String SecurityQuestion { get; set; }
public String SecurityAnswer { get; set; }
public virtual ICollection<FamilyMember> Families { get; set; }
public virtual ICollection<Relationship> Relationships { get; set; }
}
public class Relationship
{
[Key]
public Guid ID { get; set; }
[ForeignKey("Member1")]
public Guid Member1ID { get; set; }
[ForeignKey("Member2")]
public Guid Member2ID { get; set; }
public Guid RelationshipTypeID { get; set; }
public virtual RelationshipType RelationshipType { get; set; }
public virtual Member Member1 { get; set; }
public virtual Member Member2 { get; set; }
}
Here is the problem
The database table "Relationship" is being created with the following columns:
ID, Member1ID, Member2ID, RelationshipTypeID, Member_ID
Why is it creating the Member_ID column?
I've seen this post in which the user has the same type of setup, but I am unsure of how to define the InverseProperty correctly. I tried using fluent API calls but from what I can tell they will not work here since I have two foreign keys referring to the same table.
Any help would be appreciated!
Member_ID is the foreign key column which EF created for the navigation property Member.Relationships. It belongs to a third association from Member.Relationships refering to an end endpoint which is not exposed in your Relationship entity. This relationship has nothing to do with the other two relationships from Relationship.Member1 and Relationship.Member2 which also both have an endpoint not exposed in Member.
I guess, this is not what you want. You need always pairs of endpoints in two entities to create an association. One endpoint is always a navigation property. The second endpoint can also be a navigation property but it is not required, you can omit the second navigation property.
Now, what is not possible, is to associate two navigation properties (Member1 and Member2) in one entity with one navigation property (Relationships) in the other entity. That is what you are trying to do apparently.
I assume that your Member.Relationships property is supposed to express that the member is either Member1 or Member2 in the relationship, or that it participates in the relationship, no matter if as Member1 or Member2.
Unfortunately you cannot express this in the model appropriately. You have to introduce something like RelationsshipsAsMember1 and RelationsshipsAsMember2 and for these two collection you can use the InverseProperty attribute as shown in the other question. In addition you can add a helper property which concats the two collections. But this is not a mapped property but readonly:
public class Member
{
// ...
[InverseProperty("Member1")]
public virtual ICollection<Relationship> RelationshipsAsMember1 { get; set; }
[InverseProperty("Member2")]
public virtual ICollection<Relationship> RelationshipsAsMember2 { get; set; }
public IEnumerable<Relationship> AllRelationships
{
get { return RelationshipsAsMember1.Concat(RelationshipsAsMember2); }
}
}
Accessing AllRelationships will cause two queries and roundtrips to the database (with lazy loading) to load both collections first before they get concatenated in memory.
With this mapping the Member_ID column will disappear and you will only get the two expected foreign key columns Member1ID, Member2ID because now you have only two associations and not three anymore.
You could also think about if you need the Relationships collection in the Member entity at all. As said, navigation properties on both sides are not required. If you rarely need to navigate from a member to its relationships you could fetch the relationships also with queries on the Relationship set, like so:
var relationships = context.Relationships
.Where(r => r.Member1ID == givenMemberID || r.Member2ID == givenMemberID)
.ToList();
...or...
var relationships = context.Relationships
.Where(r => r.Member1ID == givenMemberID)
.Concat(context.Relationships
.Where(r => r.Member2ID == givenMemberID)
.ToList();
This would give you all relationships the member with ID = givenMemberID participates in without the need of a navigation collection on the Member entity.

Can't form some simple POCO's to use with "Code First" Entity Framework, please check for mistake

So I decided to go with the code first/DbContext approach, but already have an existing database file. Nothing complex, so I am thinking I can just create the DbContext derived container class with DbSets for the respective POCO's, create the connection string to my database and I should be set. However I believe I am having difficulties properly declaring the properties in my entity classes since I am getting errors when trying access an object through the navigational properties. Usually telling me Object reference not set to an instance of an object when I try context.Products.Find(1).Category.CATNAME; etc. Also tried declaring the collection properties with virtual keyword to no avail.
Some specifics of the database schema are:
In Categories table the PCATID is a foreign key to the CategoryID in
the same Categories table and can be null.
Both CategoryID and RootCategoryID in Products table can be null and
are both foreign keys to CategoryID in the Categories table.
I am testing things at the moment but will be setting a lot of the fields to non null types eventually.
Here are my entity POCO's and the entity Dbset container class:
public class Category
{
[Key]
public int CategoryID { get; set; }
public string CATNAME { get; set; }
public int PCATID { get; set; }
public ICollection<Category> Categories { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
[Key]
public int ProductID { get; set; }
public int CategoryID { get; set; }
public int RootCategoryID { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public string Keywords { get; set; }
public decimal ListPrice { get; set; }
public Category Category { get; set; }
}
public class EFDbContext: DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
You need to make PCATID a nullable property as you have said it can be null. Make all those navigation properties and collection properties virtual. EF will not be able to detect the category hierarchy so you have use either attributes or fluent API to configure that.
public class Category
{
[Key]
public int CategoryID { get; set; }
public string CATNAME { get; set; }
[ForeignKey("ParentCategory")]
public int? PCATID { get; set; }
[InverseProperty("Categories")]
public virtual Category ParentCategory { get; set; }
[InverseProperty("ParentCategory")]
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Requirements for Creating POCO Proxies
Everything looks ready for POCO but Lazy Loading isn't sorted out at this point. By default LL is on, but in order to enable lazy loading, the Category property must be Virtual (a proxy is created that catches the reference and loads the data). If you don't want lazy loading then disable it in your EFDbContext constructor.
So your options are:
public virtual Category Category { get; set; }
or
public class EFDbContext: DbContext
{
public static EFDbContext()
{
LazyLoadingEnabled = false
}
...
}
You'd probably want to do the first one...
Are you certain you really want to use Code First? Or do you just want to use DbContext and DbSet? You can get the same benefits with Database First, using DbContext and DbSet. Since you already have a database, it's generally a lot simpler.
See: http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
The only difference between Code First and Database First with DbContext is that Code first uses the fluent mapping model, while Database First uses an .edmx file. Maintaining the .edmx is much easier with an existing database.
If you're bound and determined to use Code First, then I suggest getting the Entity Framework Power Tools CTP1 and reverse engineering your database to Code First.
I agree with #Eranga about class Category (+1 to #Eranga).
public class Category {
[Key]
public int CategoryID { get; set; }
public string CATNAME { get; set; }
[ForeignKey("ParentCategory")]
public int? PCATID { get; set; }
[InverseProperty("Categories")]
public virtual Category ParentCategory { get; set; }
[InverseProperty("ParentCategory")]
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
And you also have problem with your Linq query:
context.Products.Find(1).Category.CATNAME;
EF return data only from tables that you request with Include or you use this tables in functions.
With this code all work:
db.Products
.Include(p => p.Category) // here I demand to load data from Category table
.First(p => p.ProductID == 3)
.Category
.CATNAME;

One-to-one plus many-to-many relationships with the same object not building correctly

I'm using the Entity Framework 4 code first approach to design my database in ASP MVC 3 and I ran into a bit of a hitch. I have a POCO class as below:
public class User
{
[Key]
public Guid UserID { get; set; }
public string UserName { get; set; }
public DateTime CreationDate { get; set; }
public string Email { get; set; }
public int Points { get; set; }
public Session ActiveSession { get; set; }
public ICollection<Session> InSessions { get; set; }
}
with Session as another one of my model classes defined elsewhere, with ICollection<User> as one of its properties. If I remove the public Session ActiveSession { get; set; } property from the User class, then the many-to-many mapping and UserSessions intermediate table are constructed correctly, but when I add the ActiveSession one-to-one mapping back in, it breaks the many-to-many mapping and the intermediate table is not constructed. Instead the Users table has a single foreign key to the Sessions table each for both the ActiveSession and InSessions properties. Any ideas why this is happening?
In your case EF thinks that ICollection<User> in Session class is the Many end of the one to many relationship created by ActiveSession.
So you need to configure mannualy
modelBuilder.Entity<User>().HasOptional(u => u.ActiveSession)
.WithMany()
.Map(u => u.MapKey("ForeignKeyColumn"));
modelBuilder.Entity<User>()
.HasMany(u => u.InSessions)
.WithMany(s => s.Users)
.Map(m =>
{
m.ToTable("UserSessions");
m.MapLeftKey("UserID");
m.MapRightKey("SessionID");
});

Why is MVC3 not scaffolding my foreign key columns

I'm trying to use MVC 3 with EF 4.1 using code first and am following Scott Guthries tutorial http://weblogs.asp.net/scottgu/archive/2011/05/05/ef-code-first-and-data-scaffolding-with-the-asp-net-mvc-3-tools-update.aspx.
The issue I'm having is that when I create the products controller and the related scaffolded views, there is no "category" column being created in any of the views ("edit", "create", "index" etc), which according to the tutorial should be created.
I've traced the reason why the column is not being shown is because of the t4 templates... it is failing a check to see if it is a bindable type in order to display the property as a column.
The logic for checking if it is bindable is:
bool IsBindableType(Type type) {
return type.IsPrimitive || bindableNonPrimitiveTypes.Contains(type);
}
Where bindableNonPrimitiveTypes is a fixed list:
static Type[] bindableNonPrimitiveTypes = new[] {
typeof(string),
typeof(decimal),
typeof(Guid),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
};
I have just installed VS2010 sp1, EF 4.1 and the MVC3 Tools Update referenced by the tutorial.
I'm sure I've followed all the steps...
Where am I going wrong/What am I missing?
I believe that it does work as described in the tutorial - I just went through that tutorial right now and got the expected result (it did scaffold a "Category" column and drop-down list).
My best guess about why it didn't work in your case is that perhaps you missed the CategoryID property from the Product class, or maybe you called it something else. For scaffolding to detect the FK relationship, it's necessary for your entity to have both a "navigation" property (in this case, Category, of type Category) and a "foreign key" property (in this case CategoryID of type int) - without those it won't infer the relationship and hence you wouldn't get the dropdown.
In case it helps, here's the full code for the model classes that you can copy and paste into your project:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public int CategoryID { get; set; }
public decimal? UnitPrice { get; set; }
public int UnitsInStock { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class StoreContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
Remember to compile your code before using the "Add Controller" window, otherwise it will not realise that you've changed the code.

Resources