I am trying to insert records in c# with Oracle database. I am using transactions for inserting.
How do I get the child objects ID to insert in upcoming next object's data? I am able to get the ID of parent but unable to get the child objects ID. parent and child are object of same class.
code looks like this:
using (DatabaseContext lContext = new DemoDatabaseContext())
{
try
{
foreach (var alias in pLstAlias)
{
DATA lAlias = new DATA();
lAlias.ID = alias.ID;
lAlias.FIRST_NAME = alias.FIRST_NAME;
lAlias.SECOND_NAME = alias.SECOND_NAME;
lAlias.NAME_CONCAT = alias.GetConcatName();
lAlias.SYSTEM_NAME = alias.GetSystemName(lAlias.NAME_CONCAT);
lAlias.Add(lContext);
if (alias.AKAList != null)
{
foreach (var aka in alias.AKAList)
{
DATA lChildAlias = DATA();
lChildAlias.PARENT_ID = lAlias.ID;
lChildAlias.AKA__NAME = aka.FIRST_NAME;
lChildAlias.NAME_CONCAT = aka.GetConcatName();
lChildAlias.SYSTEM_NAME = aka.GetSystemName(lChildAlias.NAME_CONCAT);
List<DATA2> aliasList = StoreRecodsToObject(lChildAlias.SYSTEM_NAME);
if (aliasList != null)
{
foreach (var item in aliasList)
{
DATA DataForAliases = new DATA2();
// here I need to add ID of lChildAlias
DataForAliases.ALIAS_ID = lChildAlias.ID;
DataForAliases.NAME = item.NAME;
DataForAliases.Add(lContext);
}
}
}
lChildAlias.Add(lContext);
}
}
}
}
catch(Exception ex){
lContext.Rollback();
return false;
}
}
Related
how to insert data into one-to-many relationship using linq to sql. i have two table first is person and secondly is order ,i have make a relationship between both table,i want to insert data into both table at a time
public ActionResult Add(CustomerViewData data)
{
string message = "";
var item = data.Customer;
try
{
_repositoryCustomer.Insert(item);
_repositoryCustomer.Save();
return RedirectToAction("Edit", new { message = Constants.RecordSaved, id = item.CustomerId});
}
catch (Exception ex)
{
message = "Customer had error saving.";
Log.Error(message, ex);
}
return View("Edit", new CustomerViewData { PageMode = PageMode.Add, Message = message });
}
using (MyDataContext dc = new MyDataContext())
{
Person p = new Person();
Order o = new Order();
p.Orders.Add(o); //connect the objects into an object graph.
dc.Persons.Add(p); //add the graph to the data context
dc.SubmitChanges(); //save it all.
}
I have a nested list and I need to convert it to DataSet in C#. I found many example about this but they dont do what I need. I have a list in a list, I need the nested list in another DataTable in the DataSet.
Here is an example of list
public class InvoiceResponse(){
public string BillToName { get; set; }
public string BillToAddr1 { get; set; }
...
...
public List<InvoiceItemResponse> Items { get; set; }
}
I have used the code below to convert the List to DataSet but It didnt convert Items to DataTable in DataSet
public DataSet CreateDataSet<T>(List<T> list)
{
//list is nothing or has nothing, return nothing (or add exception handling)
if (list == null || list.Count == 0) { return null; }
//get the type of the first obj in the list
var obj = list[0].GetType();
//now grab all properties
var properties = obj.GetProperties();
//make sure the obj has properties, return nothing (or add exception handling)
if (properties.Length == 0) { return null; }
//it does so create the dataset and table
var dataSet = new DataSet();
var dataTable = new DataTable();
//now build the columns from the properties
var columns = new DataColumn[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
columns[i] = new DataColumn(properties[i].Name, properties[i].PropertyType);
}
//add columns to table
dataTable.Columns.AddRange(columns);
//now add the list values to the table
foreach (var item in list)
{
//create a new row from table
var dataRow = dataTable.NewRow();
//now we have to iterate thru each property of the item and retrieve it's value for the corresponding row's cell
var itemProperties = item.GetType().GetProperties();
for (int i = 0; i < itemProperties.Length; i++)
{
dataRow[i] = itemProperties[i].GetValue(item, null);
}
//now add the populated row to the table
dataTable.Rows.Add(dataRow);
}
//add table to dataset
dataSet.Tables.Add(dataTable);
//return dataset
return dataSet;
}
How can I convert the Items list to another DataTable into the DataSet?
You can just add a bit of recursivity to your code, something like this:
var set = new DataSet();
AddToDataSet(set, resp);
...
public static void AddToDataSet(DataSet set, object value)
{
if (set == null)
throw new ArgumentNullException(nameof(set));
if (value == null)
return;
var type = value.GetType();
var table = set.Tables[type.FullName];
if (table == null)
{
// create one table per type (name)
table = new DataTable(type.FullName);
set.Tables.Add(table);
foreach (var prop in type.GetProperties().Where(p => p.CanRead))
{
if (IsEnumerable(prop))
continue;
var col = new DataColumn(prop.Name, prop.PropertyType);
table.Columns.Add(col);
}
}
var row = table.NewRow();
foreach (var prop in type.GetProperties().Where(p => p.CanRead))
{
object propValue = prop.GetValue(value);
if (IsEnumerable(prop))
{
if (propValue != null)
{
foreach (var child in (ICollection)propValue)
{
AddToDataSet(set, child);
}
}
continue;
}
row[prop.Name] = propValue;
}
table.Rows.Add(row);
}
private static bool IsEnumerable(PropertyInfo pi)
{
// note: we could also use IEnumerable (but string, arrays are IEnumerable...)
return typeof(ICollection).IsAssignableFrom(pi.PropertyType);
}
I have content items stored in Ektron that are assigned to taxonomies. I'm trying to create a method that will allow me to programmatically change the taxonomies. So far I find the content item by ID, and I'm able to retrieve its taxonomies, but I'm not sure how to change them.
var ektronItem = contentManager.GetItem((long) item.tctmd_id);
if (ektronItem != null) // item exists in Ektron
{
var newTaxonomies = item.taxonomy_ids;
var taxonomyAPI = new Taxonomy();
var taxData = taxonomyAPI.ReadAllAssignedCategory(ektronItem.Id);
foreach (var tax in taxData)
{
taxonomyAPI.RemoveTaxonomyItem(???);
// here I'm trying to remove the content item from the taxonomy
}
}
taxonomyAPI.RemoveTaxonomyItem() takes a Ektron.Cms.TaxonomyRequest object, but I'm not sure how to create this. I'm also not sure if this is even the method I should be using.
In case anyone else wants to know how to do this, here's the solution I came up with:
var contentManager = new Ektron.Cms.Framework.Content.ContentManager();
var criteria = new Ektron.Cms.Content.ContentCriteria(ContentProperty.Id, EkEnumeration.OrderByDirection.Ascending);
criteria.AddFilter(ContentProperty.FolderId, CriteriaFilterOperator.EqualTo, toUpdate.folder_id);
criteria.OrderByDirection = Ektron.Cms.Common.EkEnumeration.OrderByDirection.Descending;
criteria.OrderByField = Ektron.Cms.Common.ContentProperty.GoLiveDate;
criteria.FolderRecursive = true;
criteria.PagingInfo = new Ektron.Cms.PagingInfo(50, 1);
var ektronItem = contentManager.GetItem((long) item.tctmd_id);
if (ektronItem != null) // item exists in Ektron
{
// update taxonomy in Ektron
var taxIds = item.taxonomy_ids;
var taxonomyAPI = new Taxonomy();
var taxData = taxonomyAPI.ReadAllAssignedCategory(ektronItem.Id);
var taxManager = new Ektron.Cms.Framework.Organization.TaxonomyItemManager();
var taxCriteria = new TaxonomyItemCriteria();
// create a taxonomy criteria of the item ID
taxCriteria.AddFilter(TaxonomyItemProperty.ItemId, CriteriaFilterOperator.EqualTo, item.tctmd_id);
// get all taxonomy items with item ID
var taxItems = taxManager.GetList(taxCriteria);
// determine taxonomyItemType
var type = taxItems.FirstOrDefault().ItemType;
foreach (var tax in taxData)
{
// delete from old taxonomies
taxManager.Delete(tax.Id, (long)item.tctmd_id, type);
}
foreach (var tax in taxIds)
{
// add to new taxonomies
var taxonomyItemData = new TaxonomyItemData()
{
TaxonomyId = tax,
ItemType = type,
ItemId = (long)item.tctmd_id
};
try
{
taxManager.Add(taxonomyItemData);
}
catch (Exception ex)
{
}
}
}
I have two tables :
Table AnnonceVImg: Id, dateModif,
Table AnnonceVTxt: Id, dateModif, AnnonceVImg_Id
I want to display only the images which are not yet linked to an AnnonceVTxt, but since I don't have the AnnonceVTxt_id in AnnonceVImg I don't know how to add this condition.
Here is my controller
public PartialViewResult ListAnnonce(DateTime dateParution, long IdJournal)
{
using (var db = new Bd_scanitEntities())
{
List<ScanITAPP.ImgOrgSet> images = new List<ImgOrgSet>();
images = db.JournalSet.Find(IdJournal).ImgOrgSet.Where(i => i.dateParution == dateParution).ToList();
List<ScanITAPP.AnnonceVImgSet> annoncesVimg = new List<AnnonceVImgSet>();
foreach (var img in images)
{
annoncesVimg.AddRange(db.ImgOrgSet.Find(img.Id).AnnonceVImgSet.ToList());
}
//IEnumerable<ScanITAPP.AnnonceVImgSet> annonces;
ViewBag.IdJournal = dateParution;
ViewData["dateParution"] = dateParution.ToString("dd-MM-yyyy");
AnnonceVTxtSet annTxt = new AnnonceVTxtSet();
annTxt.Id = 0;
AnnonceVImgSet annImg = db.AnnonceVImgSet.Find(1);
annTxt.AnnonceVImgSet = annImg;
return PartialView("_ListAnnonceImg", annoncesVimg.OrderBy(i => i.dateSaisi).Distinct().ToList());
}
}
I have an empty data base.
I want to add multi records into data base.
while inserting record to data base i want to check if my product inserted in same date donot add it again(i want to change some it's filed and update it's content).
i used this code but it just add some data into data base (it can't check for existing product.)
var AllData = ClsDataBase.Database.InsertProductTbls;
foreach(item in AllData)
{
//Update
if (Exist(datefa))
{
var query = ClsDataBase.Database.CustomerProductTbls.SingleOrDefault
(data => data.CustomerId == AllData .CustomerId );
int? LastProductTotal = query.CustomerProducTtotal;
query.CustomerProducTtotal = LastProductTotal + ClsInsertProduct._InsertProductNumber;
}
//Insert
else
{
_CustomerProductTbl = new CustomerProductTbl();
_CustomerProductTbl.CustomerId = AllData ._CustomerId;
_CustomerProductTbl.CustomerProductDateFa = AllData.datefa
.
.
.
ClsDataBase.Database.AddToCustomerProductTbls(_CustomerProductTbl);
}
}
}
ClsDataBase.Database.SaveChanges();
if i use ClsDataBase.Database.SaveChanges(); for both update and insert part i will return this error:
An error occurred while starting a transaction on the provider connection. See the inner exception for details.
please help.
I got the solution by opening database conection for each repeat loop:
foreach(item in AllData)
{
using (StorageEntities context = new StorageEntities())
{
//Update
if (Exist(datefa))
{
var query = ClsDataBase.Database.CustomerProductTbls.SingleOrDefault
(data => data.CustomerId == AllData .CustomerId );
int? LastProductTotal = query.CustomerProducTtotal;
query.CustomerProducTtotal = LastProductTotal + ClsInsertProduct._InsertProductNumber;
}
//Insert
else
{
_CustomerProductTbl = new CustomerProductTbl();
_CustomerProductTbl.CustomerId = AllData ._CustomerId;
_CustomerProductTbl.CustomerProductDateFa = AllData.datefa;
ClsDataBase.Database.AddToCustomerProductTbls(_CustomerProductTbl);
}
ClsDataBase.Database.SaveChanges();
}
}