MVC One to one relationship with codefirst - c#

Iam trying to create one to one relationship with my models. But I'm getting following error: " Multiplicity is not valid in Role 'DetayAcıklama_UrunBilgi_Target' in relationship 'DetayAcıklama_UrunBilgi'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'."
My models are like below:
public class Urun
{
[Key]
public int UrunID { get; set; }
[Required]
public string UrunKodu { get; set; }
[Required]
public decimal Fiyat { get; set; }
[ForeignKey("DetayBilgi")]
public int DetayAcıklamaID { get; set; }
public DetayAcıklama DetayBilgi { get; set; }
}
public class DetayAcıklama
{
[Key]
public int DetayAcıklamaID { get; set; }
[Display(Name = "Açıklama")]
public string AcıklamaTxt { get; set; }
public decimal Fiyat { get; set; }
[Required, ForeignKey("UrunBilgi")]
public int UrunID { get; set; }
public Urun UrunBilgi { get; set; }
}
What am I missing? Thanks in advance

Your current implementation doesn't say which is dependent table on which table.. for that specify a primary key column as the foreign key:
[Key, ForeignKey("UrunBilgi")]
public int DetayAcıklamaID { get; set; }

Related

Create navigation property without foreign key

I have two classes like so:
[Table("GameLevels", Schema = "ref")]
public class GameLevel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public double PointsMin { get; set; }
public double PointsMax { get; set; }
}
[Table("GameProfiles", Schema = "usr")]
public class UserGameProfile
{
[Key]
[ForeignKey("ApplicationUser")]
public string Id { get; set; }
public int GamesPlayed { get; set; }
public double Points { get; set; }
public int WinCount { get; set; }
public int LossCount { get; set; }
public int DrawCount { get; set; }
public int ForfeitCount { get; set; }
public int GameLevelId { get; set; }
public virtual GameLevel Level { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
Entity framework builds this so that UserGameProfile has a foreign key pointing to GameLevel. I guess this is because of the GameLevelId property.
Is there any way I can get this to generate the tables and navigation property without the foreign key?
I tried:
modelBuilder.Entity<UserGameProfile>().HasOptional<GameLevel>(x => x.Level).WithMany();
But then database fails to build. With this error:
One or more validation errors were detected during model generation:
Project.Domain.Data.UserGameProfile_Level: : Multiplicity
conflicts with the referential constraint in Role
'UserGameProfile_Level_Target' in relationship
'UserGameProfile_Level'. Because all of the properties in the
Dependent Role are non-nullable, multiplicity of the Principal Role
must be '1'.
Basically what I want is a zero-or-one to zero-or-many relationship.
How do I keep levels independent but have the ability to add a level to a profile?
You can't drop the foreign key completely, otherwise, how do you expect the two entities (i.e, tables) to be linked? What you can do instead is have a nullable FK, which will effectively make the relationship zero-or-one to many.
In your GameLevel class, add a navigation property as a collection of UserGameProfile:
public class GameLevel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public double PointsMin { get; set; }
public double PointsMax { get; set; }
public virtual ICollection<UserGameProfile> UserGameProfiles { get; set; }
}
Then in the UserGameProfile class, make the property GameLevelId nullable:
public class UserGameProfile
{
// ...
// ...
public int? GameLevelId { get; set; }
[ForeignKey("GameLevelId")]
public virtual GameLevel GameLevel { get; set; }
}
This should work without even having to use Fluent API.

Error: introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

A quick question for masters.
I got 2 EF model classes:
public class School
{
public int Id { get; set; }
[DisplayName("School")]
public string Name { get; set; }
public List<Teacher> Teachers { get; set; }
public List<Note> Notes { get; set; }
}
public class Teacher
{
public int Id { get; set; }
[DisplayName("Öğretmen")]
public string Name { get; set; }
public int SchoolId { get; set; }
public School School { get; set; }
public List<Note> Notes { get; set; }
}
Basically I want to create an one to many relationship in code-first.
But when I try to do that, I get this error:
Introducing FOREIGN KEY constraint 'FK_dbo.Teachers_dbo.Schools_SchoolId' on table 'Teachers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Where have I made a mistake?
EDIT
public class Note
{
public int Id { get; set; }
[Required,DisplayName("Başlık"), StringLength(50)]
public string Title { get; set; }
[Required,DisplayName("Açıklama"), StringLength(4000)]
public string Description { get; set; }
public string File { get; set; }
public DateTime UploadDate { get; set; }
public bool IsApproved { get; set; }
public int SchoolId { get; set; }
public int OwnerId { get; set; }
public int TeacherId { get; set; }
//Keys
public School School { get; set; }
public Teacher Teacher { get; set; }
public List<Comment> Comments { get; set; }
}
I didnt get any error for this Model and Keys..
Remove the relationship from Note to School and vice versa. You could get the school by the teacher that has a relationship to the note.
It will produce your issue.

How to add composite foreign key in data annotation for Entity Framework 6

I am working on ASP.NET application with Entity Framework 6. I have already database and I am using Code First existing Database approach.
I am two table and second table has Foriegn key along with its own primary key. I have used Column order but still getting following error. I have search online, tried different combination but still getting error.
'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code Sys_Nav_FunctionHierarchyEntity_Sys_Nav_FunctionEntity_Source: : Multiplicity is not valid in Role 'Sys_Nav_FunctionHierarchyEntity_Sys_Nav_FunctionEntity_Source' in relationship 'Sys_Nav_FunctionHierarchyEntity_Sys_Nav_FunctionEntity'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
Class A
[Table("Sys_Nav_Function")]
public class Sys_Nav_FunctionEntity
{
public Sys_Nav_FunctionEntity()
{ }
[Key]
public int Function_ID { get; set; }
[StringLength(250)]
[Required(ErrorMessage = "Required Title")]
[Display(Name = "Function Title")]
public string FunctionName { get; set; }
[Required(ErrorMessage = "Required Hierarchy Level")]
[Display(Name = "Hierarchy Level")]
public int Hierarchy_Level { get; set; }
public Sys_Nav_FunctionHierarchyEntity Sys_Nav_FunctionHierarchyEntity { get; set; }
public ICollection<Sys_Nav_FunctionInActionEntity> Sys_Nav_FunctionInActionEntity { get; set; }
public ICollection<Sys_Nav_FunctionInControllerEntity> Sys_Nav_FunctionInControllerEntity { get; set; }
}
Class B
[Table("Sys_Nav_FunctionHierarchy")]
public class Sys_Nav_FunctionHierarchyEntity
{
public Sys_Nav_FunctionHierarchyEntity()
{
}
[Key, Column(Order =0)]
public int Hierarchy_ID { get; set; }
[ForeignKey("Sys_Nav_FunctionEntity"), Column(Order =1)]
public int Function_ID { get; set; }
public int Parent_Function_ID { get; set; }
public Sys_Nav_FunctionEntity Sys_Nav_FunctionEntity { get; set; }
}
Try this
[Table("Sys_Nav_FunctionHierarchy")]
public class Sys_Nav_FunctionHierarchyEntity
{
public Sys_Nav_FunctionHierarchyEntity()
{
}
[Key, Column(Order =0)]
public int Hierarchy_ID { get; set; }
[ForeignKey("Function_ID"), Column(Order =1)]
public int Function_ID { get; set; }
public int Parent_Function_ID { get; set; }
public Sys_Nav_FunctionEntity Sys_Nav_FunctionEntity { get; set; }
}
The foriegn key you have in class B is linked to the table and not to the property.
I believe the above code should give you the correct result
I think that the ForeignKey attribute should be set on the navigation property:
[Table("Sys_Nav_FunctionHierarchy")]
public class Sys_Nav_FunctionHierarchyEntity
{
//...
public int Function_ID { get; set; }
[ForeignKey("Function_ID")]
public Sys_Nav_FunctionEntity Sys_Nav_FunctionEntity { get; set; }
}
If Parent_Function_ID is also a foreign key to the same table, you can do it the same way.
Also, in the first class:
public Sys_Nav_FunctionHierarchyEntity Sys_Nav_FunctionHierarchyEntity { get; set; }
should be a collection (if I understood the probem correctly)
I have remove composite key, I have tried different combination but no luck, however its working by using same key as foreign key and also changed in database.
[Table("Sys_Nav_FunctionHierarchy")]
public class Sys_Nav_FunctionHierarchyEntity
{
public Sys_Nav_FunctionHierarchyEntity()
{
}
[Key, ForeignKey("Sys_Nav_FunctionEntity")]
[Required]
public int Function_ID { get; set; }
public int Parent_Function_ID { get; set; }
public Sys_Nav_FunctionEntity Sys_Nav_FunctionEntity { get; set; }
}

Entity Framework foreign key error in two connect class

I use Entity Framework 6.1 in ASP.NET MVC.
My model is :
public class Article
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public double Price { get; set; }
[InverseProperty("Article")]
public virtual ICollection<FormulaItem> FormulaItem { get; set; }
}
public class FormulaItem
{
[Key]
[Column(Order = 0)]
public int Id { get; set; }
[ForeignKey("IdMaster")]
public virtual Formula Formula { get; set; }
public int IdMaster { get; set; }
[ForeignKey("IdArticle")]
public virtual Article Article { get; set; }
public int IdArticle { get; set; }
public string Comment { get; set; }
public int Count { get; set; }
}
public class Formula
{
[Key]
[Column(Order = 0)]
public int Id { get; set; }
public FormulaMode Mode { get; set; }
// Wen add this line I get error
//[ForeignKey("IdArticle")]
//public virtual Article Article { get; set; }
//public int? IdArticle { get; set; }
public string Comment { get; set; }
public virtual IList<FormulaItem> Items { get; set; }
public Formula()
{
Items = new List<FormulaItem>();
}
}
This sample works fine, but when add the new poco:
// When I add this line in class formula I get error
[ForeignKey("IdArticle")]
public virtual Article Article { get; set; }
public int? IdArticle { get; set; }
to class Formula I get error:
Formula_Items_Source_Formula_Items_Target: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical
Consider using FluentAPI as it is more user-friendly:
modelBuilder.Entity<FormulaItem>()
.HasOptional(b => b.Article )
.WithMany(a => a.FormulaItem);
And in your case you must be missing another InverseProperty attribute:
[InverseProperty("FormulaItem")]
public virtual Article Article { get; set; }
I add:
modelBuilder.Configurations.Add(new FormulaConfig());
public class FormulaConfig : EntityTypeConfiguration<Formula>
{
public FormulaConfig()
{ // one-to-many
this.HasRequired(x => x.Article)
.WithOptional(x=>x.Formula)
.WillCascadeOnDelete();
}
}
but get error :
Article_Formula_Target: : Multiplicity is not valid in Role 'Article_Formula_Target' in relationship 'Article_Formula'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

Creating relationships in entity with out foreign keys

I am using the code first approach, to create the database based on modals and the db context class. The problem is that when I create the relationships between one model and the next and run the code the data base generates foreign keys like it should.
How ever I want the relationships, with out the foreign keys. is this possible to do with entity framework and the code first approach?
for example:
namespace LocApp.Models
{
public class Location
{
public int id { get; set; }
[Required]
public string name { get; set; }
[Required]
public string address { get; set; }
[Required]
public string city { get; set; }
[Required]
public string country { get; set; }
[Required]
public string province { get; set; }
[Required]
public string phone { get; set; }
public string fax { get; set; }
public bool active { get; set; }
public virtual ICollection<LocationAssignment> LocationAssignment { get; set; }
}
}
Has a relationship with:
namespace LocApp.Models
{
public class LocationAssignment
{
public int id { get; set; }
public int locationID { get; set; }
public int serviceID { get; set; }
public int productID { get; set; }
public int personID { get; set; }
public virtual Location Location { get; set; }
public virtual Service Service { get; set; }
public virtual Product product { get; set; }
public virtual Person person { get; set; }
}
}
As you can see this table will have a foreign key generated with the location table. How do I keep this relationship WITH OUT the generation of foreign keys?
User Triggers On Insert and on update and delete relative and reference tables !!! but that's not cute you must control allthing in your application instead

Categories