MVC 3 database create/insert error - asp.net-mvc

I'm getting the error
The member with identity
'UsersModel_Group' does not exist in
the metadata collection. Parameter
name: identity.
when calling the db.UsersModel.Add(SomeModel) method. I checked the controllers and models if there's any problem with namespaces but there's nothing weird that I found. I did change some classes name but there are no errors upon build. Any suggestions?
here are the classes that might be relevant:
public class UsersModel{
public int ID {get; set;}
...
[ForeignKey("GroupID")]
[Display(Name = "Group")]
public virtual GroupModel Group { get; set; }
[Required]
public virtual int GroupID { get; set; }
public virtual List<GroupModel> GroupList { get; set; }
}
public class GroupModel {
public int ID { get; set;}
...
[Required]
public int ID { get; set; }
[Required]
[StringLength(20,ErrorMessage = "The {0} must not exceed {2} characters")]
public string Name { get; set; }
}

If you've changed your model after the database was created you will need to recreate the database. EF Code First stores details of your model inside a metadata table. If this metadata does not match that of your model then you will get an error.
If you don't want to drop your database you can delete the metadata table and then manually make your database changes so that it matches your model.

Related

primary key column not visible by default

I am learning ASP.NET and trying to create two table using code first approach using MVC. Below is the model .cs file for Courses.
public class Instructor
{
[Key]
public string name { get; set; }
public string address { get; set; }
public string address_ { get; set; }
public string email { get; set; }
}
public class Course
{
[Key]
[DisplayName("Course")]
[Required(ErrorMessage = "CSExxx")]
public string progId { get; set; }
public string subject { get; set; }
public string semester { get; set; }
public string description { get; set; }
[ForeignKey("instructor")]
public virtual string name { get; set; }
public virtual Instructor instructor { get; set; }
}
I added the corresponding controller and as expected views got generated automatically by visual studio. Once I ran the project and clicked on instructor menu below is the window which got opened.
Clearly I am not able to see the column name which I declared as PK. Now when I click on Create New then I am able to see four columns including the Primary key column which is name.
My Question why I am not able to see the primary key column in the main display.
The templates and code generators at work here assume a technical key, ie one that is not visible or meaningful to the user.
Your choice of name is debatable, the simple solution here is to introduce
[Key]
public int Id { get; set; }
in all your classes. If you do want to stick to the name, then simply edit the generated cshtml.

Validation occurred client side with breeze entities for some properties which will be filled server side in the BeforeSaveEntity

I use the Durandal template in my asp.net mvc solution. The question here is related to Breeze which is also used in Durandal. Let's say I have the following entity in my model:
public class Driver
{
[Key]
public int Id { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
public string Comment { get; set; }
public int? CreatedById { get; set; }
public DateTime? CreatedTime { get; set; }
public int? UpdatedById { get; set; }
public DateTime? UpdatedTime { get; set; }
public virtual User CreatedBy { get; set; }
public virtual User UpdatedBy { get; set; }
}
As you can see, I have some properties used to track creation/updates for time and userid (UpdatedById, UpdatedTime, ...). I would like to let the user edit/create my drivers in some data entry pages then fill in these properties (UpdatedById, UpdatedTime, ...) server side automatically in the BeforeSaveEntity method.
It works but as you noted I had to allow nullable on the properties like int? or DateTime? because in case of adding a new entity (everything is blank) the validation failed if I didn't proceed like that.
My question: is there another solution or something that could be done to avoid using nullable types on my model (int? - DateTime?) for these properties which track my creation/edition?
Thanks.
Make them nonnullable and fill in "dummy" values of the client, in a "registered" ctor for each type that will then get overwritten on the server.

Code First Many-Many Error (may cause cycles or multiple cascade paths)

I have looked at so many questions and tried every solution available but it seems not to work with my specific scenario. I am trying to add a code-first many to many relationship for the below classes and receive the following error:
Introducing FOREIGN KEY constraint
'FK_dbo.AgentPoolAgents_dbo.Agents_Agent_Id' on table
'AgentPoolAgents' 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. See previous errors.
Agent
public class Agent
{
public virtual int Id { get; set; }
public virtual string AgentName { get; set; }
public virtual int UserId { get; set; }
public virtual bool Available { get; set; }
public virtual DateTime CreatedTime { get; set; }
public virtual ICollection<AgentPool> AgentPools { get; set; }
public Agent()
{
}
}
AgentPool
public class AgentPool
{
public virtual int Id { get; set; }
[Required]
[Display(Name = "Agent pool name")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
public virtual string PoolName { get; set; }
public virtual int UserId { get; set; }
public virtual DateTime CreatedTime { get; set; }
public virtual DateTime ModifiedTime { get; set; }
public virtual ICollection<Agent> Agents { get; set; }
public AgentPool()
{
}
}
UserId is a foreign key to a UserProfile class to identify the owner of agents and agentpools.
The error appears when running a migration using the update-database package manager console command.
Any help is much appreciated!
You don't need every field to be virtual. Not sure what you're trying to achieve by doing this. Use the 'virtual' keyword to eager load navigation properties, e.g. Keep ICollection Agents virtual.
In answer to your question, look at: this question.

Error with one-to-many relationship in MVC Entity Framework 4

I get the following error when I run up my code-first MVC app and try and visit either the DeveloperAccountModel details page or another view that loads a parent object and a collection of DeveloperAccountModel: The navigation property 'Redirects' is not a declared property on type 'DeveloperAccountModel'. At this point, I am not accessing the property (which does exist!) just attempting to load the DeveloperAccountModel.
[Table("sitedata")]
public class DeveloperAccountModel
{
[Required]
[RegularExpression("^[0-9]*$")]
[Display(Name = "User id")]
[Key]
[Column("_rowid")]
public long RowId { get; internal set; }
// Other properties removed
[Display(Name = "Redirects")]
[NotMapped]
[InverseProperty("DeveloperAccount")]
public List<SiteRedirectModel> Redirects { get; internal set; }
}
And then the dependent model
[Table("siteredirects")]
public partial class SiteRedirectModel
{
[Key]
[Column("_rowid")]
[Display(Name = "RowId")]
public int RowId { get; internal set; }
[Column("_siteid")]
[Display(Name = "Developer account id")]
public long DeveloperAccountModelId { get; internal set; }
[NotMapped]
[ForeignKey("DeveloperAccountModelId")]
public virtual DeveloperAccountModel DeveloperAccount { get; internal set; }
}
I have tried so many variations of the various tutorials and samples including other times where this or a similar error occurs but I am not seeing something really simple. Can anyone help please?
Simply, remove the [NotMapped] attribute from both properties. So your properties definition should look like:
// In SiteRedirectModel
[ForeignKey("DeveloperAccountModelId")]
public virtual DeveloperAccountModel DeveloperAccount { get; internal set; }
// In DeveloperAccountModel
[Display(Name = "Redirects")]
[InverseProperty("DeveloperAccount")]
public List<SiteRedirectModel> Redirects { get; internal set; }

ASP.NET MVC 3 EF Code First - How do I make a model that optionally refers to a parent of its own type?

I'm trying to create a model that can optionally refer to a parent of the same type, for example:
public class Category
{
public virtual long CategoryID { get; set; }
public virtual Category? ParentCategory { get; set; }
public virtual int UserID { get; set; }
public virtual string Name { get; set; }
}
As you can see there is an optional member called ParentCategory that is optional and refers to a class of type Category (i.e. the same type). As I'm sure you can guess, I'm trying to create a simple Category tree, where the root node(s) will not have a parent.
This results in the following error when the Entity Framework tries to create the database:
"The ForeignKeyAttribute on property 'ParentCategoryID' on type 'MyProject.Models.Category' is not valid. The navigation property 'Category' was not found on the dependent type 'MyProject.Models.Category'. The Name value should be a valid navigation property name."
I also tried this:
public class Category
{
public virtual long CategoryID { get; set; }
[ForeignKey("Category")]
public virtual long? ParentCategoryID { get; set; }
public virtual int UserID { get; set; }
public virtual string Name { get; set; }
}
But again this resulted in the same error.
Is it possible to model this using EF Code First? Its easy to model it int he database if I were to create the database manually.
Thanks in advance
Ben
Your first example wouldn't even compile because T?, a shortcut for Nullable<T> can only be applied to value types.
The following works fine here:
public class Category
{
public virtual long CategoryID { get; set; }
public virtual Category ParentCategory { get; set; }
}
Now, this will use an ugly name by default for the FK, ParentCategory_CategoryID.
This is a way to get a nicer name, plus some flexibility when using it:
public class Category
{
public virtual long CategoryID { get; set; }
[ForeignKey("ParentCategoryID")]
public virtual Category ParentCategory { get; set; }
public virtual long? ParentCategoryID { get; set; }
}

Resources