How to add an entity to an existing entity MVC 2 EF - c#

I am creating a MVC 2 website. I'm a beginner. I created a Model to use EF. The relationship is between a user table and a product table (one to many relationship). I am able to create new users and save them on the DB using linq to entities. My question is how do I add a product to an existing user. I was starting with the code below but it does not work. Intellisense doesn't see the queryuser.Product whats wrong with my code or what is the right way to do it. If someone can help me it would be great
public void Insert(Product obj)
{
if (HttpContext.Current.Session["userid"] != null)
{
string userid2 = HttpContext.Current.Session["userid"].ToString();
var queryuser = from p in entities.Users
where p.UserID == userid2
select p;
queryuser.Product.Add(obj);
entities.Users.Add(queryuser);
entities.SaveChanges();
}
}
I am calling this method from my controller.

queryuser is an IQueryable and you are treating it like a single object.
You might try replacing:
queryuser.Product.Add(obj);
entities.Users.Add(queryuser);
with
user = queryuser.First();
user.Product.Add(obj);
entities.Users.Add(user);

Related

Database query returning only the first element of the data base as the same instance for all, in ASP.NET MVC Core 6

I am having some trouble and cannot figure out why my sql database is returning the first data entry as all the other entries.This is my method to get all the database table entries from the table called HealthDataFuture
[HttpPost]
public IActionResult AjaxMethod(string id)
{
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"Months", "SOFAS"
});
//FOR SOME REASON IT KEEPS READING THE FIRST DATABASE ENTRY ONLY SO THERE ALL THE ENTRIES ARE THE SAME VALUE
foreach (HealthDataFuture data in _db.HealthDataFuture)
{
if (data.id == id)
{
chartData.Add(new object[]
{
data.Month, data.Sofas
});
}
}
return Json(chartData);
}
This is my database table entries, it's returning the first entry as all the other ones when I query all of it, they have the same id because i want to return all of them and then graph
This is the results i keep getting back
i have also tried this way of getting data however it is the same problem
-------EDIT ----- PROBLEM RESOLVED
It turns out my MYSQL table model was not created properly as there was no primary key nor foreign key
It's better not to share image, but code using correct tag. To use code helps other users and all the cummunity, for example it makes your question searchable.
Anyway you can try to do in this way:
if (!string.IsNullOrEmpty(id)){
List<HealthDataFuture> DataList = _db.HealthDataFuture.Where(x => h.Id == id).ToList();
return View(id);
}
return RedirectToAction("Index");
I've also some question about your code:
What should it do?
DataList is like a select query from db, but nobody is using DataList. Why?
The more details you provide, the more information we have to help you.
Editing after comments:
If you want to remove data from db you should use saveChanges. For example, if you want to remove all lines with id other than "1", you can try:
if (!string.IsNullOrEmpty(id)){
_db.HealthDataFuture.RemoveRange(_db.HealthDataFuture.Where(x => h.Id != id));
_db.SaveChanges();
return View(id);
}
return RedirectToAction("Index");
You can also read something about access to DB in async way, it's recommended and it perfoms better: https://learn.microsoft.com/it-it/ef/core/miscellaneous/async

Delete junction table record in Entity Framework Code First (M:M)

How do I delete a record in a junction table within Entity Framework 5?
When reverse engineering my DataContext, Entity Framework seems to have recognized my junction table and automatically added Collections to my Models to represent the M:M relationship. This is great when adding items, as I can simply build my entire Entity and everything gets inserted properly. Perfect.
However, I'm stumped on removing a relationship. For example, an Activity can have multiple Contacts associated to it, and this is linked using a junction table (dbo.ActivityContacts) that consists of the columns:
ActivityID
ContactID
Both my Activity and Contact models have been updated by EF with Collections to represent the other. For example, my Activity model looks like this:
public class Activity
{
public int ActivityID { get; set; }
public string Subject { get; set; }
public virtual ICollection<Contacts> Contacts { get; set; }
}
In a non-EF environment, I would simply delete the record from the junction table and move on with my day. However, it seems I cannot access the junction table directly using EF, so I'm a tad confused on how to remove the record (relationship).
How can I properly remove a record from a junction table in Entity Framework?
Agree with #Chris.
Another solution is to do:
context.Entry(activity).State = EntityState.Deleted;
Entity Framework should remove the record for you, if you remove the associated object from either side of the relationship.
Assuming you've obtained this Activity instance from your context and want to remove a specific Contact with a known ID:
unwantedContact = context.Contacts.Find(contactID);
myActivity.Contacts.Remove(unwantedContact);
context.SaveChanges();
Should delete the record in your junction table, unless I'm being daft.
ali golshani did a good job providing a solution. Let me try to expand on it a little more. In my scenario I have two list boxes where you can move items left or right (selected or not selected)
The 'dto' object below is sent from the client. It's checking the selected state for each item in the list. If anyone knows of any way to improve this any more please leave feedback.
file_appender selectedAppender = context.file_appender.Find(dto.Id);
int[] ids = dto.Loggers.Where(x => !x.Selected).Select(x => x.Id).ToArray();
var loggers_to_delete = selectedAppender.logger.Where(x => ids.Contains(x.id));
loggers_to_delete.ToList().ForEach(x =>
{
selectedAppender.logger.Remove(x);
});
ids = dto.Loggers.Where(x => x.Selected).Select(x => x.Id).ToArray();
var loggers_to_add = context.logger.Where(x => ids.Contains(x.id));
loggers_to_add.ToList().ForEach(x =>
{
selectedAppender.logger.Add(x);
});
Lets look at another example....This one is for a list box with embedded check boxes (a little simpler). Honestly this could probably be applied to the solution above to make easier to read code.
protected void saveRelatedConnectors(test_engine testEngine, List<int> connectorTypes)
var stepConnectorsToDelete = testEngine.step_connector.Where(x => (connectorTypes.Count == 0) ||
(connectorTypes.Count != 0 && !connectorTypes.Contains(x.id)));
stepConnectorsToDelete.ToList().ForEach(x =>
{
testEngine.step_connector.Remove(x);
});
var stepConnectorsToAdd = entities.step_connector.Where(x => connectorTypes.Contains(x.id));
stepConnectorsToAdd.ToList().ForEach(x =>
{
testEngine.step_connector.Add(x);
});
entities.SaveChanges();
contact_to_delete = context.Contacts.Find(contactID);
selected_activity = context.Activity.Find(ActivityID);
context.Entry(selected_activity).Collection("Activity").Load();
selected_activity.Contacts.Remove(contact_to_delete);
db.SaveChanges();

Create a query using LINQ to entities with 1:N relation

I know it's not something unusual to make such kind of queries but I think I get lost so I seek help. I have to tables with relation 1:N and to make it more clear I'll post a print screen from the management studio :
I am working on a asp.net mvc 3 project and I need to make a view where all Documents will be shown (and some filter and stuff, but I think that is irrelevant for this case). I need the data from the table Documents and only one specific record for each document from the DocumentFields table. This record is the record holding the name of the Document and it's uniqueness is DocumentID == Docmuents.Id, DocumentFields.RowNo == 1 and DocumentsFields.ColumnNo == 2. This is unique record for every Document and I need to get the FieldValue from this record which actually holds the Name of the Document.
I am not very sure how to build my query (maybe using JOIN) and I also would like to make my view strongly typed passing a model of type Documents but I'm not sure if it's possible, but I think depending on the way the query is build will determine the type of the model for the view.
I believe what you want is something like this:
var results =
from d in dbContext.Documents
join df in dbContext.DocumentFields
on new { d.Id, RowNo = 1, ColumnNo = 2 } equals
new { Id = df.DocumentId, df.RowNo, df.ColumnNo }
select new
{
Document = d,
DocumentName = df.FieldValue
};
Of course if you set up navigation properties, you can just do this:
var results =
from d in dbContext.Documents
let df = d.DocumentFields.First(x => x.RowNo == 1 && x.ColumnNo == 2)
select new
{
Document = d,
DocumentName = df.FieldValue
};

Crm 2011 - retrieve associated [N:N] entities (C#)

I'm writing a simple application that imports entities to CRM. Durring this import I need to associate imported entities (custom entity) to another (also custom) entities.
There's no problem with new objects, but when I try to update, I need to delete all associations regarding imported entity and recreated them based on imported data.
How can I do this?
I was thinking of getting all associated entities, and then call disassociate for each of them, but I got stuck trying to get those associated entities.
How should I approach this?
Suppose that you have Student Entity And you want to copy the student Cources to another custom Entity as you said named CStudent
You can use the following code:
var scs = Context.new_Student_CourcesSet.Where(x => x.new_courceid == Cource.Id).ToList<new_Student_Cources>();
var removedsc = Context.new_new_CStudent_CourcesSet.Where(x => x.new_cstudentid == CStudent.Id).ToList<new_CStudent_Cources>();
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
EntityReferenceCollection removedrelatedEntities = new EntityReferenceCollection();
Relationship relationship = new Relationship(new_CStudent_Cources.EntityLogicalName);
if (removedsc != null)
{
foreach (new_CStudent_Cources c in removedsc )
{
RemovedrelatedEntities.Add(new EntityReference(new_Cources.EntityLogicalName, (Guid)ar.new_courcesid));
}
Service.Disassociate(CStudent.LogicalName, CStudnetid, relationship, RemovedrelatedEntities);
}
foreach (new_Student_Cources d in scs)
{
relatedEntities.Add(new EntityReference(new_Cources.EntityLogicalName, (Guid)d.new_courceid));
}
Service.Associate(CStudent.LogicalName, CStudentid, relationship, relatedEntities);

How do I extract this LinqToSql data into a POCO object?

with my Repository classes, I use LinqToSql to retrieve the data from the repository (eg. Sql Server 2008, in my example). I place the result data into a POCO object. Works great :)
Now, if my POCO object has a child property, (which is another POCO object or an IList), i'm trying to figure out a way to populate that data. I'm just not too sure how to do this.
Here's some sample code i have. Please note the last property I'm setting. It compiles, but it's not 'right'. It's not the POCO object instance .. and i'm not sure how to code that last line.
public IQueryable<GameFile> GetGameFiles(bool includeUserIdAccess)
{
return (from q in Database.Files
select new Core.GameFile
{
CheckedOn = q.CheckedOn.Value,
FileName = q.FileName,
GameFileId = q.FileId,
GameType = (Core.GameType)q.GameTypeId,
IsActive = q.IsActive,
LastFilePosition = q.LastFilePosition.Value,
UniqueName = q.UniqueName,
UpdatedOn = q.UpdatedOn.Value,
// Now any children....
// NOTE: I wish to create a POCO object
// that has an int UserId _and_ a string Name.
UserAccess = includeUserIdAccess ?
q.FileUserAccesses.Select(x => x.UserId).ToList() : null
});
}
Notes:
Database.Files => The File table.
Database.FilesUserAccess => the FilesUserAccess table .. which users have access to the GameFiles / Files table.
Update
I've now got a suggestion to extract the children results into their respective POCO classes, but this is what the Visual Studio Debugger is saying the class is :-
Why is it a System.Data.Linq.SqlClient.Implementation.ObjectMaterializer<..>
.Convert<Core.GameFile> and not a List<Core.GameFile> containing the POCO's?
Any suggestions what that is / what I've done wrong?
Update 2:
this is what i've done to extract the children data into their respective poco's..
// Now any children....
UserIdAccess = includeUserIdAccess ?
(from x in q.FileUserAccesses
select x.UserId).ToList() : null,
LogEntries = includeUserIdAccess ?
(from x in q.LogEntries
select new Core.LogEntry
{
ClientGuid = x.ClientGuid,
ClientIpAndPort = x.ClientIpAndPort,
// ... snip other properties
Violation = x.Violation
}).ToList() : null
I think that all you need to do is to put another Linq query in here:
q.FileUserAccesses.Select(x => x.UserId).ToList()
i.e. You want to select data from the FileUserAccess records - which I'm assuming are Linq to SQL classes, so to do this you can have something like:
(from fua in q.FileUserAccesses
select new PocoType
{
UserID = fua.UserID,
Name = fua.User.UserName // Not sure at this point where the name comes from
}).ToList()
That should get you pointed in the right direction at least.
What is the type of UserIdAccess? How is it not 'right'? Are you getting the 'wrong' data? if so have you checked your database directly to make sure the 'right' data is there?

Categories