I have an MVC 4 application that is using code first to generate tables and columns in my SQL Server DB. I am trying to figure out how I ended up with an additional TABLE that was not intended. I have looked through some questions but not found the exact same problem I am having. I will try to explain this simply.
I have added a model called Associate which keeps track of associates that my client does business with. Each Associate needs a foriegn key of AssociateTypedID and RegionID.
namespace XXX.Models
{
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual ICollection<AssociateType> AssociateTypes { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
}
AND
namespace XXX.Models
{
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class Region
{
public int RegionId { get; set; }
public int RegionName { get; set; }
public int RegionDescription { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class XXXDb : DbContext
{
public XXXDb(): base("name=DefaultConnection")
{
}
public DbSet<Associate> Associates { get; set; }
public DbSet<AssociateType> AssociateTypes { get; set; }
public DbSet<Region> Regions { get; set; }
}
}
So I have updated my code above and I'm getting very close to where I need to be in my database. I have the following tables generated.
Associates, AssociateTypes & Regions (each of them have the columns I would expect)
BUT I now have a new table called RegionAssociates which has the following columns:
Region_RegionId (int) & Associate_AssociateId (int)
This table was not expected or needed in my schema.
Your classes doesn't match your description of the model. You are saying
Each Associate can have a designation of AssociateType
I suppose that the same AssociateType can be assigned to more Associates, so there should be 1:N relationship between AssociateType and Associate.
But the Associate class defines the relationship the other way around - by convention public virtual ICollection<AssociateType> AssociateType { get; set; } creates 1:N relationship between Associate and AssociateType.
the correct definition of your classes would be
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual AssociateType AssociateType { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
Can't say for sure what is missing from your configuration as you did't post it, but if you are using the fluent api something like this should fix the problem:
modelBuilder.Entity<AssociateType>()
.HasKey(t => t.AssociateTypeId);
modelBuilder.Entity<Associate>()
.HasRequired(t => t.AssociateType)
.WithRequiredPrincipal(t => t.Associate);
The above is adapted from this article http://msdn.microsoft.com/en-us/data/jj591620.aspx
Related
My Entities:
public partial class Student: IBrand
{
public Student()
{
Grades = new HashSet<Grade>();
}
[Key]
public int StudentId { get; set; }
[ForeignKey("Users")]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
[ForeignKey("Parent")]
public int? ParentId { get; set; }
public Parent Parent { get; set; }
public int? SectionId { get; set; }
public string FatherName { get; set; }
public int classNumber { get; set; }
public Section Section { get; set; }
public string brevetResult { get; set; }
public DateTime? dateLeftAec { get; set; }
public string additionalInfo { get; set; }
public bool bacc { get; set; }
public string baccResult { get; set; }
public string baccSection { get; set; }
public int BrandId { get; set; }
[JsonIgnore]
public Brand Brand { get; set; }
public virtual ICollection<StudentRegistration> StudentReg { get; set; }
public virtual ICollection<Grade> Grades { get; set; }
public virtual ICollection<Absence> Absences { get; set; }
public virtual ICollection<StudentStudyYear> StudentStudyYears { get; set; }
}
public class Grade: IBrand
{
public int gradeId { get; set; }
public int grade { get; set; }
public int StudentId { get; set; }
public int SubjectId { get; set; }
public int TeacherId { get; set; }
public int TermId { get; set; }
public int SectionId { get; set; }
public bool IsApproved { get; set; }
public string ResultToEdit { get; set; }
public bool IsEditedByAdmin { get; set; }
public virtual Student Student { get; set; }
public virtual Subject Subject { get; set; }
public virtual Teacher Teacher { get; set; }
public virtual Term Term { get; set; }
public virtual Section Section { get; set; }
public int BrandId { get; set; }
[JsonIgnore]
public Brand Brand { get; set; }
public virtual ICollection<GradeStudyYear> GradeStudyYears { get; set; }
}
I'm trying to get a student with his grades, but I encountered a problem with circular references. I tried to add this to the startup file:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
That seemed to solve the circular references problem, but then I started getting 5GB worth of data... so that code apparently just suppressed the error without solving the circular data problem.
I tried to put the attribute [JSONIgnore] in my grade.cs file, but I need to get a student from grade so it will not be useful.
How can I solve this circular references problem?
Serializing entities leads to a number of issues and exposes more information about your domain than is needed. When returning data to a view or an API consumer you can instead define a view model or DTO to contain just the details that consumer will need in whatever structure best serves that need. This avoids reference issues which EF navigation properties can cause, reduces the amount of domain knowledge and data you expose to clients, and minimizes the payload size to just what is needed. Data can be flattened, so if you are displaying a list of one entity, you don't need a ViewModel/DTO per related entity, your view model can merely contain relevant details of any related entity that applies to that consumer.
Once you have defined your view model / DTO you can use .Select() to populate it, or set up mapping with Automapper and populate it using .ProjectTo<TViewModel>().
Ι am having a json like this:
{"userTweetsList":[{"tweetId":1,"tweetData":"testing uploading from uwp","createdTime":1510822592529,"commentCount":0,"likeCount":1,"flagCount":1,"mediaUrl":"suburl","tweetUser":"geo.thomas","userLiked":true,"userFlagged":true},{"tweetId":2,"tweetData":"Testing tweet","createdTime":1510821224655,"commentCount":0,"likeCount":0,"flagCount":1,"mediaUrl":"suburl","tweetUser":"sreejith.sree","userLiked":false,"userFlagged":true}],"tweetUsersMapList":[{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}},{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}],"urlFileserverDynamic":"MyBaseUrl"}
My model class:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
In my cs file, I link the listview with the userTweetsList, My listview name is ListView1.
ListView1.ItemsSource = userTweetResponse.userTweetsList;
I can access the all the data in the userTweetsList using {binding} property.
My problem is I need to access and show the name in ui based on the tweet user value. Suppose the "tweetUser":"geo.thomas" i need to access the
{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}} inside the tweetUsersMapList, same way for "tweetUser":"sreejith.sree"
i need the data
{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}
For this I change the model like this:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
public class TweetUsersMapList
{
public string username { get; set; }
public string name { get; set; }
public string profileImage { get; set; }
}
But i don't know how to do the rest part. How can i link the listview with tweetUsersMapList? Based on the tweetUser name how can i pick the name and show that in the ui?
Is it possible to parse this type of complex json?
Anybody, please suggest a solution
Thanks in advance...
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public object createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
}
public class GeoThomas
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class SreejithSree
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class TweetUsersMapList
{
public GeoThomas __invalid_name__geo.thomas { get; set; }
public SreejithSree __invalid_name__sreejith.sree { get; set; }
}
public class RootObject
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
public string urlFileserverDynamic { get; set; }
}
I have used Json2csharp to generate these classes...
i have a report where i display some subclasses values. It's working well for some, but not for others and i don't know why. The models :
[Serializable]
public partial class CompanyProvider
{
public int CompanyProviderId { get; set; }
public string CompanyNo { get; set; }
public string LPID { get; set; }
public string VATNo { get; set; }
public int? CompanyProviderAddressId { get; set; }
[ForeignKey("CompanyProviderAddressId")]
public virtual CompanyProviderAddress CompanyProviderAddress { get; set; }
public int? CompanyProviderAddressBillingId { get; set; }
[ForeignKey("CompanyProviderAddressBillingId")]
public virtual CompanyProviderAddressBilling CompanyProviderAddressBilling { get; set; }
public int? CompanyProviderContactManagerId { get; set; }
[ForeignKey("CompanyProviderContactManagerId")]
public virtual CompanyProviderContactManager CompanyProviderContactManager { get; set; }
public int? CompanyProviderBankId { get; set; }
[ForeignKey("CompanyProviderBankId")]
public virtual CompanyProviderBank CompanyProviderBank { get; set; }
...
}
[Serializable]
public partial class CompanyProviderBank
{
public int CompanyProviderBankId { get; set; }
public int? BankId { get; set; }
public virtual Bank Bank { get; set; }
public string Postcode { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
}
[Serializable]
public partial class CompanyProviderAddress
{
public int CompanyProviderAddressId { get; set; }
public string Postcode { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
}
It's working for CompanyProviderAddress and CompanyProviderAddress which have only "simple" properties (string, int...), but it doesn't work for CompanyProviderContactManager and CompanyProviderBank which have complex properties (like Bank for CompanyProviderBank).
Everything is serializable, this is working in my report :
=First(Fields!CompanyProviderAddress.Value.City(), "CompPro")
But this doesn't works, give me an #Error
=First(Fields!CompanyProviderBank.Value.City(), "CompPro")
Any idea? Or maybe someone knows how to get more details about #error, something more explicit?
Thx
It is possible your objects are null.
You can check if they are null like this:
=IIF(IsNothing(First(Fields!CompanyProviderBank.Value.City)), 0,First(Fields!CompanyProviderBank.Value.City))
I'm not entirely sure the above is in the correct syntax, please let me know if it isn't.
I have 2 models, A Order Header and Order Detail.
I want to end up with a JSON reply from the Server that looks like:
--OrderHeader 1
|
--OrderDetails 1
--OrderHeader 2
|
--Order Detail 2
Would I use entity framework create some sort of sub query wand return this via my WebGet, or would I run separate queries and integrate the format after the results have been obtained?
Here are my Viewmodels:
public class OpenOrderHeader
{
public int CustomerID { get; set; }
public int OrderID { get; set; }
public int OrderUniqueNumber { get; set; }
public int NumberOfProductsOnOrder { get; set; }
public DateTime OrderDateCreated { get; set; }
public DateTime OrderDateUpdated { get; set; }
public string OrderLocalOnline { get; set; }
public int BranchID { get; set; }
public string PaymentMethod { get; set; }
public int OrderStatus { get; set; }
public string OrderCurrency { get; set; }
public decimal OrderConversionRate { get; set; }
public decimal SubTotalInclTax { get; set; }
public decimal SubTotalExclTax { get; set; }
public decimal DiscountInclTax { get; set; }
public decimal DiscountExclTax { get; set; }
public decimal ShippingInclTax { get; set; }
public decimal ShippingExclTax { get; set; }
public decimal PaymentFeeInclTax { get; set; }
public decimal PaymentFeeExclTax { get; set; }
}
public class OpenOrderProducts
{
public int OrderID { get; set; }
public string ProductSKUName { get; set; }
public int ProductSKUID { get; set; }
public string ProductSKUStockCode { get; set; }
public DateTime ProductAddedToOrder { get; set; }
public int QtyOfProductsOnOrder { get; set; }
public decimal UnitPriceinclTax { get; set; }
public decimal UnitPriceExclTax { get; set; }
public decimal UnitDiscountInclTax { get; set; }
public decimal UnitDiscountExclTax { get; set; }
public decimal LineItemTotalIncludingTax { get; set; }
public decimal LineItemExclTax { get; set; }
public decimal LineItemShippingCost { get; set; }
}
Just create a navigation property Orderdetails on the OrderHeader entity. Then you can query
var data = db.OrderHeaders.Include(h => h.Orderdetails).ToList();
and serialize data into JSON.
I think that in the classes you show OpenOrderHeader would have a collection of OpenOrderProducts?
public virtual ICollection<OpenOrderProduct> OpenOrderProducts { get; set; }
(As you see, I would change the name of the class in OpenOrderProduct, no plural)
I am building a simple application with EF 4.1 Code First, but I am stuck. Here's an ERD of my application Domain Model:
In Visual Studio 2010, I have a solution with two projects in it. One project is to house the Domain Model, the other is an MVC3 Web Application to house the application logic.
In the Class Libraries (Project 1), I have the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace QuotesDomain
{
public class QuoteContext : DbContext
{
public DbSet<Quote> Quotes { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Language> Languages { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<QTBridge> QTBridge { get; set; }
}
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public virtual Author Author { get; set; }
[Required]
public virtual Language Language { get; set; }
public virtual ICollection<QTBridge> TagsBridge { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Language
{
public int Id { get; set; }
[Required, MaxLength(20), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Tag
{
public int Id { get; set; }
[Required, MaxLength(40), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<QTBridge> QuotesBridge { get; set; }
}
public class QTBridge
{
public int Id { get; set; }
public int QuoteId { get; set; }
public int TagId { get; set; }
}
}
I've been watching some video tutorials, and the above looks good to me, but when I try and run the application, I get the following error:
Are my Code First classes correct based on the ERD Diagram? What do I need to do to solve the error?
Here's the full listing of code for Entities and configuration.
public class QuoteContext : DbContext
{
public DbSet<Quote> Quotes { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Language> Languages { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//This will create create a join table "QuoteTags"
modelBuilder.Entity<Quote>().HasMany(q => q.Tags)
.WithMany(t => t.Quotes);
}
}
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool IsApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public int AuthorId { get; set; }
[ForeignKey("AuthorId")]
public virtual Author Author { get; set; }
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public virtual Language Language { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool IsApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Language
{
public int Id { get; set; }
[Required, MaxLength(20), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Tag
{
public int Id { get; set; }
[Required, MaxLength(40), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes{ get; set; }
}