Simple insertion through asp MVC3 EntityFramework - asp.net

i have two simple models that have one-many relation
public class X{
public int id {get;set;}
public virtual Y y{ get; set; }
public string description{get;set;}
}
public class Y{
public int id{get;set;}
public string name{get;set;}
}
and from the entity framework i set the relation
I'm trying to submit a form that creates a new X record with existing Y value
the returned data from the form to the action is the string description and y_id.
on the action when i try to specify the object from the parameters
public ActionResult sth(X x){}
the x.y is set to null (which is expected...) while when i tried the following ...
x.y = (from i in Y where i.id == that_id select i).first();
...
db.saveChanges();
the entity framework inserted a new Y record to the database ...
i know that i'm doing something wrong ... your help will be very appreciated !

Looking at the code you have an ID for x and y with a Virtual Y in x. Along with this Virtual Y in x you will also need a reference to y's id. Along with a Virtual ICollection of x in y.
public class X{
public int x_id {get;set;}
public int y_id {get;set}
public virtual Y y{ get; set; }
public string description{get;set;}
}
public class Y{
public int y_id{get;set;}
public string name{get;set;}
public virtual ICollection<X> X {get;set;}
}
This helps the relationship in entity. You may also want to pass a list of y(s) to the controller in charge of your form, unless you already selecting your y value from a dropdown on the form.

It seems an issue with tracking Y objects in the dbContext. how are you generating the collection Y you querying with linq? do you fetch it from the database using a dbContext? or from some other source?
if not, you need to be fetching it using a context or using the Attach() function so it could be properly tracked.
Another question pops up. how come a new Y is inserted? Don't you have a primary key defined in the database? or is it try to insert then an exception is thrown?
These are my thoughts on the matter.

Related

Pull external data into model in ASP.NET MVC

I am new to MVC. I went through the getting started guide for MVC 5 by Microsoft and have some really basic understanding of how things work. What I am looking to do is create a view page which display data from my domain model and related data that is not part of the domain model (the related data is on another sql server which I am not inserting or updating records. It's just related data I can associate with the data in my domain model).
For simplicity lets say I have a domain model that includes:
Student with Id Firstname, LastName, CourseId
Course with Id, Name, Department, ExtraInfoId
and I want to create another "model" (not sure if model is the correct term for this)
ExtraInfo with ExtraInfoId, Time, Location
The ExtraInfo is related to the Course by ExtraInfoId. ExtraInfo won't be in the database I am creating or updating. It is a external database that I want to connect to and pull data out of for display purpose, exampe get a student's Firstname, the course taken and then any "ExtraInfo" related to the Course.
I hope this makes sense. Any information or some quick sample code would be much appreciated.
Thanks!
Let's assume you have two class, one for your model
public class Student{
public string Name {get;set;}
public string LastName {get;set;}
public int CourseId {get;set;}
public string Name {get;set;}
public string Department {get;set;}
public ExtraInfo ExtraInfos {get;set}
}
public class ExtraInfo {
public int ExtraInfoId {get;set;}
public DateTime? Time {get;set;}
public string Location {get;set;}
}
Then in you controller you valorize first the Student class, then the ExtraInfos property of the student class and return the student class to you view, as a viewmodel.
var student = GetMyStudent(id); //method for accessing your student's data, could be linq with EF, or a httpclient call
student.ExtraInfos = GetExtraInfo(id); //same
return View(student);

Entity Framework swaps navigational properties

I am using EF with DB first approach. I am facing an issue while updating the EDMX file. Suppose I have a table InvoiceT and another table LookupT. Now, in InvoiceT I have a column InvoiceType having FK relation with LookupT. Now entity creates a navigational property in InvoiceT class with the name LookupT. So far, its good.
Now I added another column with name InvoiceStatus and FK with LookupT. Now entity creates another navigational property with the name LookupT1. But the issue here is that first navigational property LookupT is not pointing to its original data i.e. InvoiceType. Instead, its pointing to InvoiceStatus data now. Can anybody please explain to me why its behaving like this and what can I do about it?
public class InvoiceT
{
public int InvoiceId {get;set;}
public int InvoiceStatusLkpId {get;set;}
public int InvoiceTypeLkpId {get;set;}
public virtual LookupT LookupT {get;set;} // Previously pointing to Type. Now to Status.
public virtual LookupT LookupT1 {get;set;} // Pointing to Type
}
public class LookupT
{
public int LookupId {get;set;}
public string LookupValue {get;set}
public virtual ICollection<InvoiceT> InvoiceT {get;set;}
public virtual ICollection<InvoiceT> InvoiceT1 {get;set;}
}
So I figured out the issue. Seems like when EF creates the navigational properties, it does this in order of FK relation names i.e. if I have two FK relations with name RelationA and RelationB, then the navigational property for RelationA will be created first and then for RelationB. In my scenario, the relation names for my type and status were 'FK_InvoiceT_LookupT_InvoiceTypeLkpId' and 'FK_InvoiceT_LookupT_InvoiceStatusLkpId' (which SQL designer generates automatically) respectively and EF first generated the navigational property for the relation that was added later and it messed up my ordering. So all I had to do was to update relation names in order in which they were added and everything started working fine.

Implement Tag database

Well hi everyone I'm kinda new on Asp.net Mvc, and need some help to improve, in my project that I'm working at, I need to register a user and in the register the user must choose some tags that are categories related to the subject of my website, the thing is that i have a database that looks like this
Tag
public int TagId{get;set;}
public string TagName{get;set;}
public string TagColor{get;set;}
TagUser
public int TagUserId{get;set;}
public int UserId{get;set;}
I read that EF constructs the tables when there is a many to many relationship, it construct the middle table automatically so in my case do i just need to have the first model and my user model? or should i use the 2 models above plus the user model, with the second approach i don't know how to relate de data i can define the TagUserId as primary key and UserId as foreignkey and relate the tables, but do i need this? or can i do that with the first approach if someone can give me a tip i appreciate a lot. :)
Ps: Sorry for my bad English
You can keep a Tags property of type IList<Tag> in your User class and a Users property in your Tag class of type IList<User>. Entity Framework will create a third table to store the many to many association between Tag and User.
public class Tag
{
public int Id {set;get;}
public string TagName {set;get;}
public virtual IList<User> Users { get; set; }
}
public class User
{
public int Id {set;get;}
public string UserName {set;get;}
public virtual IList<Tag> Tags { get; set; }
}

Add/insert a new entry containing complex type in Entity Framework 7 Code first

I am trying to add a new entry for my object model which has few complex type, using EF 7 code first. But it's not working and throwing exception.
Model:
public class Student
{
public int id {get; set;}
public string Name {get; set;}
public Address Address {get; set;} -> complex type
}
public class Address
{
public int Id {get;set;}
public string Location {get;set;}
}
Code first code:
class SchoolContext {
DbSet<Student> Students {get; set;}
DbSet<Address> Addresses {get; set;}
}
var context = new SchoolContext();
context.Students.Add(new Student { Id = 1, Name = "XYZ", Address = new Address { Id = 2, Location = "US" } } -> The add method has second parameter which says include dependent objects, and by default it is true.
context.SaveChanges();
This throws exception:
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Student_Address_AddressId\". The conflict occurred in database \"School\", table \"dbo.Address\", column 'Id'.\r\nThe statement has been terminated."}
This error I think means, the Address object does not exists in database, and if I add the address first and then Student, it works. But this is just too much code, as in my real application objects has many complex types.
Ideally this should work, but it does not.
Based on this bug report, you should add item before.
It is considered as-designed. At least until RC2.

Auto generated unique number column on each update

I'm using Asp.Net MVC 5 + Entity Framework 6. Suppose I have this model:
public class ModelName
{
[Key]
public int Id { get; set; }
public int UniqueColumn { get; set; }
}
Now I want the UniqueColumn to be updated whenever I use db.SaveChangesAsync(); (meaning on both INSERTs and UPDATEs).
I tried to use DatabaseGeneratedOption.Identity but it won't update after the insert. I tried setting it to 0 but it gives me an error indicating that I can't modify an Identity column.
What do you mean by "to be updated"? You need to make it +1 on each action?
IF that is the case, try to make it static and access by class name, so it will not depend on object of this class. After update or insert action just do
ModelName.UniqueColumn++;

Resources