Hi all the below solution works in that it creates a record in the MeetingRoomRequest table and also adds the associated amenities to that request into the MeetingRoomRequestAmenityLink table. However it just feels a bit clunky, so I was wondering if there is a nicer solution out there (i.e. not having to create 2 context instances) using MVC 3 and Entity Framework??
Please note i've set up the necessary relationships (one to many) in SQL Server and Entity Framework.
Also please note AmenityList is an array of id's (e.g. [1,2,4])
private readonly IDataRepository<MeetingRoomRequest> _meetingRoomRequestRepository = new DataRepository<MeetingRoomRequest>();
private readonly IDataRepository<MeetingRoomRequestAmenityLink> _meetingRoomRequestAmenityLinkRepository = new DataRepository<MeetingRoomRequestAmenityLink>();
var meetingRoomRequestToAdd = new MeetingRoomRequest
{
User = meetingRoomRequestViewModel.User,
UserEmail = meetingRoomRequestViewModel.UserEmail,
Title = meetingRoomRequestViewModel.Title,
Comments = meetingRoomRequestViewModel.Comments,
StartDateTime = meetingRoomRequestViewModel.StartTime,
EndDateTime = meetingRoomRequestViewModel.EndTime,
RequestStatusID = (int)Enums.RequestStatus.New,
AttendeeCount = meetingRoomRequestViewModel.AttendeeCount,
AttendeeType = meetingRoomRequestViewModel.AttendeeType,
OfficeID = meetingRoomRequestViewModel.OfficeId,
LocationID = meetingRoomRequestViewModel.LocationId,
};
_meetingRoomRequestRepository.Add(meetingRoomRequestToAdd);
_meetingRoomRequestRepository.SaveChanges();
var meetingRoomRequestAdded = meetingRoomRequestToAdd;
foreach (var item in meetingRoomRequestViewModel.AmenityList)
{
var meetingRoomRequestAmenityLinkToAdd = new MeetingRoomRequestAmenityLink
{
AmenityID = item,
MeetingRoomRequestID = meetingRoomRequestAdded.MeetingRoomRequestID
};
_meetingRoomRequestAmenityLinkRepository.Add(meetingRoomRequestAmenityLinkToAdd);
_meetingRoomRequestAmenityLinkRepository.SaveChanges();
}
The way you are going about it looks right, but there are some improvements that could be made in efficiency of processing the request.
Since these are a child/parent relationship, you can create the parent entity and then attached the childern in the foreach loop before you call save changes on the parent entity. EF will automatically populate the foreign key value on the child object with the primary (or associated key) from the parent.
You can continue to use your Entity without having to save it back out to a variable. EF's object tracking will continue to track this throughout your function.
By moving the savechanges outside of the foreach loop, you are reducing the number of calls. I believe the same amount of SQL will be sent on the one final call, but you may see increases of not having the connection open/close. There may be other built in efficiencies as well from EF
The Code
var meetingRoomRequestToAdd = new MeetingRoomRequest
{
User = meetingRoomRequestViewModel.User,
UserEmail = meetingRoomRequestViewModel.UserEmail,
Title = meetingRoomRequestViewModel.Title,
Comments = meetingRoomRequestViewModel.Comments,
StartDateTime = meetingRoomRequestViewModel.StartTime,
EndDateTime = meetingRoomRequestViewModel.EndTime,
RequestStatusID = (int)Enums.RequestStatus.New,
AttendeeCount = meetingRoomRequestViewModel.AttendeeCount,
AttendeeType = meetingRoomRequestViewModel.AttendeeType,
OfficeID = meetingRoomRequestViewModel.OfficeId,
LocationID = meetingRoomRequestViewModel.LocationId,
};
_meetingRoomRequestRepository.Add(meetingRoomRequestToAdd);
foreach (var item in meetingRoomRequestViewModel.AmenityList)
{
meetingRoomRequestToAdd.MeetingRoomRequestAmenityLinks.Add(new MeetingRoomRequestAmenityLink
{
AmenityID = item
});
}
_meetingRoomRequestRepository.SaveChanges();
Related
I'm working on a MVC .NET application using EF.
I have a JqGrid in my view which works correctly bringing data from one table, but the information that I need is in two databases and three tables (Database is not normalized correctly, it sucks). I already have my two context (edmx) created in my project, I just had no idea on how to proceed in my Model. Here is my query which works fine in SQL Server
SELECT
a.idPlanta, a.idArticulo, b.DescripcionCorta, c.Planta,
a.FechaAlta, a.Existencia
FROM
CAT_ArticulosEnPlanta AS a
INNER JOIN
CAT_Articulos AS b ON a.idArticulo = b.idArticulo
INNER JOIN
[LEC].[dbo].[Plantas] AS c ON a.idPlanta = c.PlantaID
ORDER BY
b.DescripcionCorta ASC;
and here is my model that brings information from one table
public List<ArticulosPlantaView> GetArticulosEnPlanta()
{
List<ArticulosPlantaView> articuloss = new List<ArticulosPlantaView>();
using (TemakaSoftTestEntities TSTE = new TemakaSoftTestEntities())
{
ArticulosPlantaView APV;
foreach (CAT_ArticulosEnPlanta a in TSTE.CAT_ArticulosEnPlanta)
{
APV = new ArticulosPlantaView();
APV.idArticulo = a.idArticulo;
APV.idPlanta = a.idPlanta;
APV.idUsuarioAlta = a.idUsuarioAlta;
APV.FechaAlta = a.FechaAlta;
APV.Existencia = a.Existencia;
APV.Comentarios = a.Comentarios;
APV.idUsuarioElimina = a.idUsuarioElimina;
APV.FechaEliminacion = a.FechaEliminacion;
APV.Visible = a.Visible;
articuloss.Add(APV);
}
return articuloss;
}
}
public ArticulosPlantaDataView GetArticulosPlantaDataView()
{
ArticulosPlantaDataView APDV = new ArticulosPlantaDataView();
List<ArticulosPlantaView> articuloss = GetArticulosEnPlanta();
APDV.articulos = articuloss;
return APDV;
}
An example will help a lot.
THANK YOU VERY MUCH!!!
What I am trying to do is create a record in 2 tables, Communities and CommunityTeams. Each of these have a primary key ID which is set as a Identity 1.1 in SQL Server. Now, I would like to capture the key of Communities as a foreign key in CommunityTeams, but I have no way of knowing what that ID is.
Here is my code in ASP.NET MVC and Entity Framework:
if (ModelState.IsValid)
{
// Community Info
model.CommunityType = Convert.ToInt32(fc["communityType"]);
model.ComunityName = fc["communityName"];
model.CommunityCity = fc["communityCity"];
model.CommunityState = fc["communityState"];
model.CommunityCounty = fc["communityCounty"];
model.Population = Convert.ToInt32(fc["communityPop"]);
// Save to Database
model.Active = true;
model.DateCreated = DateTime.Now;
model.CreatedBy = User.Identity.Name;
model.Application_Complete = true;
model.Application_Date = DateTime.Now;
model.Payment_Complete = true;
model.Payment_Date = DateTime.Now;
model.Renewal = true;
model.Renewal_Date = DateTime.Now;
team.TeamLeader = true;
team.Admin = true;
var user = User.Identity.Name;
team.UserName = user.ToString();
team.CommunityId = 1;
db.CommunityTeams.Add(team);
db.Communities.Add(model);
db.SaveChanges();
return RedirectToAction("Index", "Habitats");
}
I will admit that you have a navigation property to Community in your CommunityTeam entity.
Replace team.CommunityId = 1; by team.Community = model;. Then simply add the team entity, EF will create both model and team.
db.CommunityTeams.Add(team);
db.SaveChanges();
You can also split the save in two parts by calling db.SaveChanges(); between the two Add call.
The first save will create the Community entity, EF will fill your primary key automatically so you can use it in Team entity for the second save.
I am using dtSearch on combination with a SQL database and would like to maintain a table that includes all DocIds and their related FileNames. From there, I will add a column with my foreign key to allow me to combine text and database searches.
I have code to simply return all the records in the index and add them one by one to the DB. This, however, takes FOREVER, and doesn't address the issue of how to simply append new records as they are added to the index. But just in case it helps:
MyDatabaseContext db = new StateScapeEntities();
IndexJob ij = new dtSearch.Engine.IndexJob();
ij.IndexPath = #"d:\myindex";
IndexInfo indexInfo = dtSearch.Engine.IndexJob.GetIndexInfo(#"d:\myindex");
bool jobDone = ij.Execute();
SearchResults sr = new SearchResults();
uint n = indexInfo.DocCount;
for (int i = 1; i <= n; i++)
{
sr.AddDoc(ij.IndexPath, i, null);
}
for (int i = 1; i <= n; i++)
{
sr.GetNthDoc(i - 1);
//IndexDocument is defined elsewhere
IndexDocument id = new IndexDocument();
id.DocId = sr.CurrentItem.DocId;
id.FilePath = sr.CurrentItem.Filename;
if (id.FilePath != null)
{
db.IndexDocuments.Add(id);
db.SaveChanges();
}
}
To keep the DocId in the index you must use the flag dtsIndexKeepExistingDocIds in the IndexJob
You can also look the dtSearch Text Retrieval Engine Programmer's Reference when the DocID is changed
When a document is added to an index, it is assigned a DocId, and DocIds are always numbered sequentially.
When a document is reindexed, the old DocId is cancelled and a new DocId is assigned.
When an index is compressed, all DocIds in the index are renumbered to remove the cancelled DocIds unless the dtsIndexKeepExistingDocIds flag is set in IndexJob.
When an index is merged into another index, DocIds in the target index are never changed. The documents merged into the target index will all be assigned new, sequentially-numbered DocIds, unless (a) the dtsIndexKeepExistingDocIds flag is set in IndexJob and (b) the indexes have non-overlapping ranges of doc ids.
To improve your speed you can search for the word "xfirstword" and get all documents in an index.
You can also look to the faq How to retrieve all documents in an index
So, I used part of user2172986's response, but combined it with some additional code to get the solution to my question. I did indeed have to set the dtsKeepExistingDocIds flag in my index update routine.
From there, I only wanted to add the newly created DocIds to my SQL database. For that, I used the following code:
string indexPath = #"d:\myindex";
using (IndexJob ij = new dtSearch.Engine.IndexJob())
{
//make sure the updated index doesn't change DocIds
ij.IndexingFlags = IndexingFlags.dtsIndexKeepExistingDocIds;
ij.IndexPath = indexPath;
ij.ActionAdd = true;
ij.FoldersToIndex.Add( indexPath + "<+>");
ij.IncludeFilters.Add( "*");
bool jobDone = ij.Execute();
}
//create a DataTable to hold results
DataTable newIndexDoc = MakeTempIndexDocTable(); //this is a custom method not included in this example; just creates a DataTable with the appropriate columns
//connect to the DB;
MyDataBase db = new MyDataBase(); //again, custom code not included - link to EntityFramework entity
//get the last DocId in the DB?
int lastDbDocId = db.IndexDocuments.OrderByDescending(i => i.DocId).FirstOrDefault().DocId;
//get the last DocId in the Index
IndexInfo indexInfo = dtSearch.Engine.IndexJob.GetIndexInfo(indexPath);
uint latestIndexDocId = indexInfo.LastDocId;
//create a searchFilter
dtSearch.Engine.SearchFilter sf = new SearchFilter();
int indexId = sf.AddIndex(indexPath);
//only select new records (from one greater than the last DocId in the DB to the last DocId in the index itself
sf.SelectItems(indexId, lastDbDocId + 1, int.Parse(latestIndexDocId.ToString()), true);
using (SearchJob sj = new dtSearch.Engine.SearchJob())
{
sj.SetFilter(sf);
//return every document in the specified range (using xfirstword)
sj.Request = "xfirstword";
// Specify the path to the index to search here
sj.IndexesToSearch.Add(indexPath);
//additional flags and limits redacted for clarity
sj.Execute();
// Store the error message in the status
//redacted for clarity
SearchResults results = sj.Results;
int startIdx = 0;
int endIdx = results.Count;
if (startIdx==endIdx)
return;
for (int i = startIdx; i < endIdx; i++)
{
results.GetNthDoc(i);
IndexDocument id = new IndexDocument();
id.DocId = results.CurrentItem.DocId;
id.FileName= results.CurrentItem.Filename;
if (id.FileName!= null)
{
DataRow row = newIndexDoc.NewRow();
row["DocId"] = id.DocId;
row["FileName"] = id.FileName;
newIndexDoc.Rows.Add(row);
}
}
newIndexDoc.AcceptChanges();
//SqlBulkCopy
using (SqlConnection connection =
new SqlConnection(db.Database.Connection.ConnectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName =
"dbo.IndexDocument";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(newIndexDoc);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
newIndexDoc.Clear();
db.UpdateIndexDocument();
}
Here is my new solution with AddDoc method from the SearchResults interface:
First get the StartingDocID and the LastDocID from the IndexInfo and walk the loop like this:
function GetFilename(paDocID: Integer): String;
var
lCOMSearchResults: ISearchResults;
lSearchResults_Count: Integer;
begin
if Assigned(prCOMServer) then
begin
lCOMSearchResults := prCOMServer.NewSearchResults as ISearchResults;
lCOMSearchResults.AddDoc(GetIndexPath(prIndexContent), paDocID, 0);
lSearchResults_Count := lCOMSearchResults.Count;
if lSearchResults_Count = 1 then
begin
lCOMSearchResults.GetNthDoc(0);
Result := lCOMSearchResults.DocDetailItem['_Filename'];
end;
end;
end
I have created an ADO.NET entity data model, and using linq to update/edit my oracle database.
using (Entities ent = new Entities())
{
RUSHPRIORITYRATE rp = new RUSHPRIORITYRATE();
rp.RATE = rate;
var query = from j in ent.RUSHPRIORITYRATEs
select j;
List<RUSHPRIORITYRATE> list = query.ToList();
if (list.Count == 0)
{
ent.AddToRUSHPRIORITYRATEs(rp);
ent.SaveChanges();
}
else
{
foreach (RUSHPRIORITYRATE r in query)
{
r.RATE = rp.RATE;
}
ent.SaveChanges();
}
}
I have a method that either adds or updates a Table that will always have one record. The record's value is then only update once there is one record in place. Adding to the table is no problem, but I've looked up how to update recores through MSDN, and "ent" does not seem to have the "submitchanges" method that the solution requires. Running this, I get the error: "The property 'RATE' is part of the object's key information and cannot be modified."
I want to remove some special characters in a table of database. I've used strong typed table to do it. When i got all data into dataset from database and modified it then i called method update() of data adapter to turn dataset to database but it doesn't work.
Below is my code
DsTel tel = new DsTel();
DsTelTableAdapters.telephone_bkTableAdapter adapter = new DsTelTableAdapters.telephone_bkTableAdapter();
adapter.Connection = new SqlConnection(ConfigurationManager.AppSettings["SiteSqlServer"].ToString());
adapter.Fill(tel.telephone_bk);
foreach (DsTel.telephone_bkRow row in tel.telephone_bk.Rows)
{
row.telephoneNo = RemoveWhiteSpace(row.telephoneNo.ToString());
row.AcceptChanges();
}
tel.AcceptChanges();
adapter.Update(tel.telephone_bk);
Please give me some ideas?
Thanks in advance.
I've found the solution for this problem by using the TableAdapterManager.
Below is my code:
DsTel tel = new DsTel();
DsTelTableAdapters.telephone_bkTableAdapter adapter = new DsTelTableAdapters.telephone_bkTableAdapter();
adapter.Connection = new SqlConnection(ConfigurationManager.AppSettings["SiteSqlServer"].ToString());
adapter.Fill(tel.telephone_bk);
foreach (DsTel.telephone_bkRow row in tel.telephone_bk.Rows)
{
if (!row.IstelephoneNoNull())
{
row.telephoneNo = RemoveWhiteSpace(row.telephoneNo.ToString());
}
}
DsTelTableAdapters.TableAdapterManager mrg = new DsTelTableAdapters.TableAdapterManager();
mrg.telephone_bkTableAdapter = adapter;
mrg.BackupDataSetBeforeUpdate = true;
mrg.UpdateAll((DsTel)tel.GetChanges());
You've called AcceptChanges before the update. This means the dataset has no changes any more so there is nothing to send to the database.
Remove all of the calls to AcceptChanges and add one AFTER the update. ie:
DsTel tel = new DsTel();
DsTelTableAdapters.telephone_bkTableAdapter adapter = new DsTelTableAdapters.telephone_bkTableAdapter();
adapter.Connection = new SqlConnection(ConfigurationManager.AppSettings["SiteSqlServer"].ToString());
adapter.Fill(tel.telephone_bk);
foreach (DsTel.telephone_bkRow row in tel.telephone_bk.Rows)
{
row.telephoneNo = RemoveWhiteSpace(row.telephoneNo.ToString());
}
adapter.Update(tel.telephone_bk);
tel.telephone_bk.AcceptChanges();