I have a problem with a Self-Referencing Code-First Entity. Our code is like this:
public class Contact
{
[Key]
public Guid Id { get; set; }
[ForeignKey("AssignedCompany")]
public Guid? AssignedCompanyId { get; set; }
[InverseProperty("AssignedContacts")]
public virtual Contact AssignedCompany { get; set; }
[InverseProperty("AssignedCompany")]
public virtual ICollection<Contact> AssignedContacts { get; set; }
}
If I want to start a Add-Migration (EF 5), I got the following Errormessage that Add-Migration can´t find a Principalend between Contact and Contact.
What do I do wrong?
Does anybody know the answer?
Thanks a lot. Kind regards
Christian Maaß
The InverseProperty Attribute should only be used when you have multiple relationships between classes. You can solve your issue by removing all the InverseProperty attributes.
Do like so, and it will work:
[ForeignKey("AssignedCompany")]
public Guid? AssignedCompanyId { get; set; }
public virtual Contact AssignedCompany { get; set; }
public virtual ICollection<Contact> AssignedContacts { get; set; }
Related
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.
This is my project model :
public class Project
{
public int ProjectID { get; set; }
public string ProjectTitle { get; set; }
public string ProjectDetails { get; set; }
public virtual ICollection<Proposal> Proposals{ get; set; }
}
This is my Proposal model :
public class Proposal
{
public int ProposalID { get; set; }
public string BidTitle { get; set; }
public string BidDetails { get; set; }
public virtual Project Project { get; set; }
}
As you can see, there is one-to-many relationship between Project and Proposal. In
mydomain/Project/Details/ProjectID
view, I want to put a button, when this button is clicked, user can create a new Proposal for that project. My question is how I can pass that project's information to bid? If you can give me some tips about it, I'd be really glad. Thanks.
Create a model known as a viewmodel, which includes both the models you want to use under the same view. Your would look something like this:
public class ProposalAndProjectModel
{
public Proposal Proposal { get; set; }
public Project Project{ get; set; }
}
Save it as something like ProposalAndProjectModel.cs and then in your view, reference this model.
Now in your view you will be able to do the following:
Model.Proposal.propertyName
or
Model.Project.propertyName
This should help you as for getting the correct parameters for creating new objects.
You say when user click button user goto another page. You can sen projectID as get to that page. Thats how you can get that projectID.
I found several questions on here relating to this but I'm not quite there. I'm trying to add a second UserProfile property to the already existing CourseRegistration class. When I try to perform the migration I get "The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.CourseRegistrations_dbo.UserProfile_InstructorId"
I thought I could solve it with some fluent configuration but it had no effect. Based on what I've read I think the issue is that there is existing data that won't allow this.
Question 1: I don't completely understand what it's complaining about and would like to understand it better if anyone could shed some light.
Question 2: Is there any workaround other than dropping the table or removing the data? I don't mind doing that this time, but I'm sure there are situations where that's not an option.
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class CourseRegistration
{
[Key]
public int RegistrationId { get; set; }
public int UserId { get; set; }
public int? InstructorId { get; set; }
public virtual UserProfile user { get; set; }
public virtual UserProfile Instructor { get; set; }
}
Thanks,
joel
See this, and try this:
public class CourseRegistration
{
[Key]
public int RegistrationId { get; set; }
public virtual UserProfile user { get; set; }
[ForeignKey("InstructorId")]
public virtual UserProfile Instructor { get; set; }
}
First of all ASP.NET and MVC 4 are very new to me (+- one month) and sorry if its a bad question.
I've got two classes "Turma" and "Curso"
public class Turma
{
[Key]
public int idCurso { get; set; }
public string RefTurma { get; set; }
public Curso Curso { get; set; }
public string NomeCurso { get; set; }
}
and
public class Curso
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int idArtigoAT { get; set; }
public string ConteudoPrograma { get; set; }
public virtual ICollection<Turma> Turmas { get; set; }
}
After this I started a migration and updated the database. So far so good, but then problems.
Due to new information the primary key type should be varchar(18). I've tried to change but so far without success.
Any ideia or solution???
No, what you want is an 'Id' property and an 'MyCustomUniqueName' property. this custom property, should be and unique index in database. this is the best design for this situation IMHO.
I've got 2 entities:
public class School
{
public int Id { get; set; }
...
public virtual ICollection<Seminar> Seminars { get; set; }
}
public class Seminar
{
public int Id { get; set; }
...
public virtual ICollection<School> Schools { get; set; }
public virtual ICollection<Price> Prices { get; set; } // wrong??
}
public class Price
{
public int Id { get; set; }
public decimal Value { get; set; }
public virtual School School { get; set; }
public virtual Seminar Seminar { get; set; }
}
How to map "Price" property for getting something like this:
var priceOfSomeSeminar = someSchool.Seminars[0].Price
Is it possible? So I think I need help with the Fluent API modelBuilder relationship establishment...
Well, ICollection doesn't have an indexer, so you can't use array syntax with it. You can, however, convert it to an IEnumerable and then convert that to a List, which can then be indexed.
But no, you are using the correct semantics, so this should just work. No need to work with the fluent api.
I think you have an error though, Price should not have a School member. There is no direct relationship between price and school.