In a function I pass a list of related values and loop over them to save changes in the database. All works well until 2 or more people use the same page to update different entities .Then only that data gets saved for which the changes were made more recently.
public bool UpdatePermanentDifferenceBL(List<PermanentDifferenceProperties> permDiffDetails)
{
try
{
int permanentDifferenceID=0;
int taxEntityID = 0;
int mapid = 0;
//using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
//{
Topaz.DAL.PermanentDifference permDiff;
for (int i = 0; i < permDiffDetails.Count; i++)
{
if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
{
using (var ctx = new TopazDbContainer())
{
try
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
catch (System.Data.OptimisticConcurrencyException ex)
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
ctx.Refresh(System.Data.Objects.RefreshMode.StoreWins, permDiff);
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
}
}
//ctx.ContextOptions.UseLegacyPreserveChangesBehavior = true;
}
//}
//using (UnitOfWork uow = new UnitOfWork())
//{
// for (int i = 0; i < permDiffDetails.Count; i++)
// {
// if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
// {
// Repository.PermanentDifferenceRepository pDiffRepo = new Repository.PermanentDifferenceRepository(uow);
// Topaz.DAL.PermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID);
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// else
// {
// int snapshotID = (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]);
// SnapShotPermanentDifferenceRepository pDiffRepo = new SnapShotPermanentDifferenceRepository(uow);
// SnapShotPermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID,snapshotID);
// permDiff.SnapshotID = snapshotID;
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// }
// uow.SaveChanges();
return true;
}
catch (Exception ex)
{
TopazErrorLogs.AddTopazErrorLogBL(ex, 1, 1);
throw new TopazCustomException(GlobalConstant.errorMessage);
}
}
Any urgent assistance is much appreciated.
The common way to solve this is adding additional column to every table where you want to handle concurrency. This column will have ROWVERSION or TIMESTAMP data type. Once you map tables in EDMX you will get a new computed property of type byte[] and set its Concurrency mode to fixed. This setting will force EF to add additional WHERE condition to every UPDATE or DELETE statement validating that row version is the same as it was when the record was loaded from the database. If the row version is not the same (another thread updated the record) the record from modification is not found and you will get exception.
Database will change the value every time you update the record automatically. You just need to ensure that your entity uses the value which was retrieved when the entity was loaded from the database.
Apologies all the viewstate and to some extent session was the culprit and not EntityFramework.
Related
This is controller code. Here I have provide how I'm creating enterprise. But currently I'm unable to create enterprise without enterprise token. Which I'm getting from customer, when customer registering thyself on play.google.com.
<!-- begin snippet: js hide: false console: true babel: false -->
using Google.Apis.Auth.AspNetCore3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.AndroidManagement.v1;
using Google.Apis.Services;
using Microsoft.AspNetCore.Mvc;
using Google.Apis.AndroidManagement.v1.Data;
using System.Security.Claims;
using Newtonsoft.Json;
using QRCoder;
using System.Drawing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
namespace xProducts_RETL.Web.Controllers
{
public class EmmController : Controller
{
private readonly ILoggerManager _loggerManager;
private readonly IEmmMapper _iEmmMapper;
private readonly IConfiguration _iConfiguration;
private SignInManager<IdentityUser> _signInManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IHostingEnvironment _environment;
private readonly UserManager<IdentityUser> _userManager;
//private static readonly string ProjectId = "xpdemo";
private static readonly string ProjectId = "xdemo";
private static readonly string PolicyId = Zoo_ManagedPolicy";
private static readonly string PolicyId2 = "Zoo_WorkPolicy";
private static readonly string PolicyId3 = "Zoo_ManagedPolicyx";
//private static readonly string COSU_APP_PACKAGE_NAME = "com.google.android.apps.work.clouddpc";
//private static readonly string TestEnterpriseName = "enterprises/xxxxj";
private static readonly string TestEnterpriseName = "enterprises/xxxx8";
private const string Package_Outlook = "com.microsoft.office.outlook";
public EmmController(ILoggerManager loggermanager, IEmmMapper iEmmMapper, IConfiguration iConfiguration, SignInManager<IdentityUser> signInManager, RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager,IHostingEnvironment environment)
{
_loggerManager = loggermanager;
_iEmmMapper = iEmmMapper;
_iConfiguration = iConfiguration;
_signInManager = signInManager;
_userManager = userManager;
_roleManager = roleManager;
_environment = environment;
}
[HttpGet]
public IActionResult CreateEnterprise(EnterpriseDto enterpriseDto, string x)
{
try
{
//bind dropdowns
enterpriseDto.EnterpriseList = _iEmmMapper.GetEnterpriseList();
enterpriseDto.CreatedEnterpriseList = _iEmmMapper.GetGooglePlaySignedupEnterpriseList();
//fetch superadmin info
var superadminData = _userManager.GetUsersInRoleAsync("SuperAdmin").Result;
var superadminId = superadminData[0].Id;
var enterpriseList = _iEmmMapper.GetEnterprises().Where(x => x.OwnerIdentityId == superadminId && x.EnrollmentToken != null && x.EnrollmentTokenWP != null).ToList();
foreach (var enterprise in enterpriseList)
{
enterpriseDto.EnterpriseId = enterprise.EnterpriseId;
}
//
return View(enterpriseDto);
}
catch (Exception ex)
{
_loggerManager.LogError($"Something went wrong inside CreateEnterprise get action: {ex.Message}");
return View(enterpriseDto);
}
}
[HttpPost]
public IActionResult CreateEnterprise(EnterpriseDto enterpriseObj)
{
//populate default dropdown values
EnterpriseDto enterpriseModel = new();
enterpriseModel.EnterpriseList = _iEmmMapper.GetEnterpriseList();
enterpriseModel.CreatedEnterpriseList = _iEmmMapper.GetEnterpriseList();
if (enterpriseObj.Id != 0 || enterpriseObj.Id2 != 0)
{
#region serviceAccountAuthenctiactionFlow
//read service a/c creds
ServiceAccountCredential? credential;
string fileName = "service_account_key.json";
string path = Path.Combine(this._environment.WebRootPath, "ZeroTouchCredJSON", fileName);
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped("https://www.googleapis.com/auth/androidmanagement")
.UnderlyingCredential as ServiceAccountCredential;
}
// Create a zero-touch enrollment API service endpoint.
var service = new AndroidManagementService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ResourceMsg.EMMAppName
});
#endregion
//create signup url
var signupData = service.SignupUrls.Create();
signupData.ProjectId = ProjectId;
signupData.CallbackUrl = _iConfiguration.GetValue<string>("AppSetting:CallBackURL");
var response = signupData.Execute();
if (response != null)
{
//create enterprise
var enterpriseData = service.Enterprises.Create(new Enterprise());
enterpriseData.ProjectId = ProjectId;
enterpriseData.SignupUrlName = response.Name;
enterpriseData.EnterpriseToken = "EAJmqckyhc_cep8KkQ-NDU3SG4uC7WfJk1oumRM9SqDPZ-jzMY6D-K-bbWaYHMDvMNsc-faLjwLdyF50yTZIKv_JK_vxEXxp2rPVKkDxzce8whACXz261yaM";
var enterpriseResponse = enterpriseData.Execute();
}
}
return View(enterpriseModel);
}
//[GoogleScopedAuthorize(AndroidManagementService.ScopeConstants.Androidmanagement)]
//[HttpPost]
//public async Task<IActionResult> CreateEnterprise([FromServices] IGoogleAuthProvider auth, EnterpriseDto enterpriseObj)
//{
// EnterpriseDto enterpriseModel = new();
// try
// {
// //bind dropdowns
// enterpriseModel.EnterpriseList = _iEmmMapper.GetEnterpriseList();
// enterpriseModel.CreatedEnterpriseList = _iEmmMapper.GetEnterpriseList();
// if (enterpriseObj.Id != 0 || enterpriseObj.Id2 != 0)
// {
// #region OAuthFlow
// // Check if the required scopes have been granted.
// if (await auth.RequireScopesAsync(AndroidManagementService.ScopeConstants.Androidmanagement) is IActionResult authResult)
// {
// return authResult;
// }
// //The required scopes have now been granted.
// GoogleCredential cred = await auth.GetCredentialAsync();
// var service = new AndroidManagementService(new BaseClientService.Initializer
// {
// HttpClientInitializer = cred.CreateScoped(AndroidManagementService.Scope.Androidmanagement),
// ApplicationName = ResourceMsg.EMMAppName
// });
// //Fetch client information from GCP
// dynamic name = "";
// dynamic email = "";
// if (User.Identity is ClaimsIdentity claimsIdentity)
// {
// var listk = claimsIdentity.Claims.Select(x => new { x.Type, x.Value }).ToList();
// name = listk[3].Value;
// email = User.FindFirstValue(ClaimTypes.Email);
// }
// //noob | superadmin
// if (email != "xy#gmail.com")
// {
// TempData["VerificationFailed"] = "You have logged in with a customer account. Please login with owner account to continue.";
// return View();
// }
// //var enterpriseRes = _iEmmMapper.GetEnterprises().Where(x=> x.ClientEmail == email);
// //if(enterpriseRes!= null)
// //{
// // TempData["MsgSignupFailed"] = "There is already an Enterprise exist. Please try with a different mail to add a new Enterprise.";
// // return View(enterpriseModel);
// //}
// #endregion
// //check userId existance
// string ownerUserId = "";
// var users = _userManager.Users.ToList();
// foreach (var user in users)
// {
// if (user.Email == "xx#yopmail.com")
// {
// ownerUserId = user.Id;
// break;
// }
// }
// //Enterprise Signup
// if (enterpriseObj.Id != 0 && enterpriseObj.ActionFlag == "Signup")
// {
// //create signup url
// var signupData = service.SignupUrls.Create();
// signupData.AccessToken = cred.UnderlyingCredential.GetAccessTokenForRequestAsync().Result;
// signupData.ProjectId = ProjectId;
// signupData.CallbackUrl = _iConfiguration.GetValue<string>("AppSetting:CallBackURL");
// //signupData.Service.
// var response = signupData.Execute();
// var ownerGoogleAccountId = User.FindFirstValue(ClaimTypes.Email);
// if (ownerGoogleAccountId != null && ownerUserId != null)
// {
// //assign client info to model
// enterpriseObj.ClientName = name;
// enterpriseObj.ClientEmail = email;
// //assign signup data to vmodel
// enterpriseObj.SignupUrlName = response.Name;
// enterpriseObj.SignupUrlURL = response.Url;
// enterpriseObj.OwnerIdentityId = ownerUserId;
// enterpriseObj.OwnerGoogleAccountId = ownerGoogleAccountId;
// //insert data into database
// var result = _iEmmMapper.CreateUpdateEnterprise(enterpriseObj);
// if (result == 1)
// {
// TempData["MsgSignupUrl"] = "Signup URL for the enterprise generated successfully.";
// return View(enterpriseModel);
// }
// }
// TempData["VerificationFailed"] = "Please login with current account details.";
// return View(enterpriseModel);
// }
// //Create Enterprise
// if (enterpriseObj.Id2 != 0 && enterpriseObj.ActionFlag == "Enterprise")
// {
// var response = _iEmmMapper.GetEnterprises().Where(x => x.Id == enterpriseObj.Id2).FirstOrDefault();
// if (response != null)
// {
// var enterpriseData = service.Enterprises.Create(new Enterprise());
// enterpriseData.AccessToken = cred.UnderlyingCredential.GetAccessTokenForRequestAsync().Result;
// enterpriseData.ProjectId = ProjectId;
// enterpriseData.SignupUrlName = response.SignupUrlName;
// enterpriseData.EnterpriseToken = response.EnterpriseToken;
// //enterprise generated
// var enterpriseResponse = enterpriseData.Execute();
// enterpriseModel.EnterpriseNameAPIFormat = enterpriseResponse.Name;
// var EnterpriseNameResponse = enterpriseResponse.Name;
// //enterpriseModel.EnterpriseToken = enterpriseData.EnterpriseToken;
// //fetch enterprise from db
// //var resultEnterprise = _iEmmMapper.GetEnterprises();
// //if (resultEnterprise != null)
// //{
// // foreach (var enterprise in resultEnterprise)
// // {
// //if (enterprise.ClientEmail == email)
// //{
// //prepare commonpolicies obj
// CommonPoliciesDto commonPolicies = new();
// //initialize model to assign apps into it
// commonPolicies.ApplicationDtoList = new List<ApplicationsDto>();
// var appModel = new ApplicationsDto();
// //enterprise Id >noob
// string[] enterpriseFullId = enterpriseResponse.Name.Split('/');
// string enterpriseId = enterpriseFullId[1];
// //create two different new policies
// string[] enterpriseArr = response.EnterpriseNameRequested.Split(' ');
// string enterpriseFirstName = enterpriseArr[0];
// string ManagedProfilePolicyName = enterpriseFirstName + "_FMDefaultPolicy";
// string WorkProfilePolicyName = enterpriseFirstName + "_WPDefaultPolicy";
// //var IsPolicyIdExist = _iEmmMapper.GetDevices().Where(x => x.PolicyId == PolicyId3 && x.EnterpriseId == enterpriseId).Any();//noob
// //if (IsPolicyIdExist)
// //{
// // SetDefaultPoliciesForExistingPolicy(TestEnterpriseName, PolicyId3);
// //}
// //else
// //{
// // //if policyId not assigned previously with any token
// // GenereateEnrollmentTokenForNewPolicy(TestEnterpriseName, PolicyId3);
// //}
// var IsManagedPolicyIdExist = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyId == ManagedProfilePolicyName && x.EnterpriseId == enterpriseId).Any();//noob
// if (!IsManagedPolicyIdExist)
// {
// //if policyId not assigned previously with any token
// GenereateEnrollmentTokenForNewPolicy(EnterpriseNameResponse, ManagedProfilePolicyName, ResourceMsg.FullyManged);
// }
// var IsWorkPolicyIdExist = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyId == WorkProfilePolicyName && x.EnterpriseId == enterpriseId).Any();//noob
// if (!IsWorkPolicyIdExist)
// {
// //if policyId not assigned previously with any token
// GenereateEnrollmentTokenForNewPolicy(EnterpriseNameResponse, WorkProfilePolicyName, ResourceMsg.Work);
// }
// #region localFunctionToGenerateTokenThruEnterpriseIdAndPolicyId
// void GenereateEnrollmentTokenForNewPolicy(string enterpriseNameAPIFormat, string myPolicyId, string policyProfileType)
// {
// //forming policy name
// string policyName = enterpriseNameAPIFormat + ResourceMsg.POLICIES_FORMAT + myPolicyId;
// //set a default hardware policy to newly registered device
// var appliedPolicyData = service.Enterprises.Policies.Patch(DefaultHardwarePolicies(myPolicyId), policyName).Execute();
// if (appliedPolicyData != null)//noob
// {
// enterpriseModel.PolicyName = policyName;
// //Create Default Policy in Database
// CommonPoliciesDto commonPoliciesModel = new()
// {
// UserIdentityId = ownerUserId,
// EnterpriseId = enterpriseId,
// PolicyId = myPolicyId,
// PolicyName = policyName,
// PolicyType = "Default",
// PolicyProfileType = policyProfileType,
// PolicyNameApiFormat = policyName,
// //
// MaximumTimeToLock = 0,
// StatusBarDisabled = false,
// KeyguardDisabled = false,
// WifiConfigDisabled = false,
// MobileNetworksConfigDisabled = false,
// BluetoothDisabled = true,
// BluetoothContactSharingDisabled = true,
// UsbFileTransferDisabled = true,
// AdjustVolumeDisabled = true,
// ScreenCaptureDisabled = true,
// ShareLocationDisabled = true,
// AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED,
// CameraDisabled = true
// };
// var result = _iEmmMapper.CreateUpdateCommonPolicies(commonPoliciesModel);
// if (result == 0)
// {
// //TempData["MsgCmnPolicies"] = ResourceMsg.PoliciesCreatedSuccessfully;
// }
// var rtrvPolicy6 = _iEmmMapper.GetCommonPolicies().ToList();
// var rtrvPolicy = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyId == myPolicyId).FirstOrDefault();
// if (rtrvPolicy != null)
// {
// if (rtrvPolicy.PolicyProfileType == ResourceMsg.FullyManged)
// {
// //create enrollmentToken for Fully Managed Device with a policy name & assign created user
// //removed to setup KIOSK mode -> .SetUser(user.AccountIdentifier)
// EnrollmentToken token = new DemoEnrollmentToken().SetPolicyName(myPolicyId).SetDuration(ResourceMsg.ThirtyDaysInSecond).SetAllowPersonalUsage(ResourceMsg.PERSONAL_USAGE_DISALLOWED);
// var tokenResponse = service.Enterprises.EnrollmentTokens.Create(token, enterpriseNameAPIFormat).Execute();
// var eToken = tokenResponse.Value;
// enterpriseModel.EnrollmentToken = eToken;
// }
// else
// {
// if (rtrvPolicy.PolicyProfileType == ResourceMsg.Work)
// {
// //User setup [can't be use in KIOSK mode setup or only work for work profile]
// var user = new User
// {
// AccountIdentifier = Guid.NewGuid().ToString()
// };
// //create enrollmentToken for work profile Device with a policy name & assign created user
// EnrollmentToken token2 = new DemoEnrollmentToken().SetPolicyName(myPolicyId).SetUser(user.AccountIdentifier).SetDuration(ResourceMsg.ThirtyDaysInSecond).SetAllowPersonalUsage(ResourceMsg.PERSONAL_USAGE_ALLOWED);
// var tokenResponse2 = service.Enterprises.EnrollmentTokens.Create(token2, enterpriseNameAPIFormat).Execute();
// var eToken2 = tokenResponse2.Value;
// enterpriseModel.EnrollmentTokenWP = eToken2;
// }
// }
// }
// else
// {
// _loggerManager.LogError($"There is an error occured in GenereateEnrollmentTokenForNewPolicy local function. {ResourceMsg.InvalidPolicy}");
// TempData["Failure"] = ResourceMsg.InvalidPolicy;
// }
// }
// }
// #endregion
// enterpriseModel.Id = enterpriseObj.Id2;
// enterpriseModel.EnterpriseId = enterpriseId;
// if (enterpriseModel.Id != 0 && enterpriseModel.EnterpriseId != null)
// {
// //update data into database
// var entResponse = _iEmmMapper.CreateUpdateEnterprise(enterpriseModel);
// if (entResponse == 1)
// {
// TempData["MsgEnterprise"] = ResourceMsg.EnterpriseCreatedSuccessfully;
// }
// }
// //}
// // }
// //}
// }
// else
// {
// TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
// }
// }
// }
// return View(enterpriseModel);
// }
// catch (Google.GoogleApiException gex)
// {
// string msgErr = "Error in " + this.GetType().ToString();
// _loggerManager.LogError($"{msgErr}{gex.Message}");
// TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
// return View(enterpriseModel);
// }
// catch (Exception ex)
// {
// string msgErr = "Error in " + this.GetType().ToString();
// _loggerManager.LogError($"{msgErr}{ex.Message}");
// TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
// return View(enterpriseModel);
// }
//}
I'm facing this issue from a long time. Please share your feedback and help on this. Any help is appreciable.
There are two ways to create an enterprise:
Customer-managed enterprise: This is the recommended way to create an enterprise. This is the one you are using in your code and it requires an enterprise token.
EMM-managed enterprise: This is not the preferred method to create an enterprise, but it is still possible to create and manage an EMM-managed enterprise using this method. EMM managed enterprises can be created programmatically without customer intervention.
This guide covers how to create EMM-managed enterprises. With this method, EMMs have full control over an enterprise’s lifecycle.
Note: In the future, it would not be possible to create any EMM-managed enterprises using the enterprises.create method.
I suggest reviewing the process of creating a Customer-managed Enterprise by having the Enterprise IT admin complete the sign-up flow, as this is the preferred method.
hallo i have this sniped code like this:
public static void Put_CSVtoSQL_Adhesion()
{
bool IsFirst = true;
DataTable dt = new DataTable();
string line = null;
int i = 0;
try
{
string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName);
using (StreamReader sr = File.OpenText(fileName))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(';');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
// Pour enlever la tete
if (!IsFirst) dt.Rows.Add(row);
IsFirst = false;
}
}
}
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn))
{
int CountColl = dt.Columns.Count;
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
copy.DestinationTableName = "cotisation";
copy.WriteToServer(dt);
}
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
this code work well, but now i have more than 60 column, should i type manualy from 1 to 60 column or there are another methode ?
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
...until 60 column ?
the column is all the same i just shifted 1 column, because the first one is autoincremented column as an ID
Write a loop?
for (int i = 0; i < dt.Columns.Count - 1; i++)
{
copy.ColumnMappings.Add(i, i + 1);
}
In the following code I expect the Original Value to be different to the new value that I have set.
Why does my test fail? I am using EF 6.1.0
The Original Value is being incorrectly set to the new value.
[TestMethod]
public void CheckOriginalAndNew()
{
var dbContext = new ProjectContext();
var proj = dbContext.Projects.Find( 1);
proj.Description = Guid.NewGuid().ToString();
DbSet<Project> dbSet = dbContext.Set<Project>();
dbSet.Add(proj);
foreach (var entry in dbContext.ChangeTracker.Entries())
{
entry.State = System.Data.Entity.EntityState.Modified;
}
ObjectContext objectContex = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContex.DetectChanges();
var entries =
objectContex.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Modified);
foreach (ObjectStateEntry entry in entries.Where(e => e.Entity is LoggedEntity && !e.IsRelationship))
{
for (int i = 0; i < entry.CurrentValues.FieldCount; i++)
{
string fieldName = entry.CurrentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name;
int ordinal = entry.OriginalValues.GetOrdinal(fieldName);
if (fieldName == "Description")
{
object newValue = entry.CurrentValues[ordinal];
object oldValue = entry.OriginalValues[ordinal];
Assert.AreNotEqual(newValue, oldValue); // fails! Why?
}
}
}
}
The reason the original value matches the current value is that the entry has been added instead of modified.
Instead of
DbSet<Project> dbSet = dbContext.Set<Project>();
dbSet.Add(proj);
I should have used
dbContext.Entry(proj).State = System.Data.Entity.EntityState.Modified;
In my Entity Framework, I have three related entities 'Client', 'ClientAddress' and 'LookupAddressType'. "LookupAddressType" is a master class specifying the type of available address type, like business address, residential address etc. ClientAddress depend on LookupAddresstype and Client. While saving a Client entity with relevant ClientAddress data, i'm getting following error.
"Violation of PRIMARY KEY constraint 'PK_LookupAddressType'. Cannot
insert duplicate key in object 'dbo.LookupAddressType'. The statement
has been terminated.
I do not need LookupAddressType to be inserted. Here I just need the relevant lookupAddressTypeId to be inserted in clientAddress entity.
The Saving code is like this:
Add(Client);
_objectContext.SaveChanges();
how can i do this?
The Load Code is below:
private void LoadClientDetails(EFEntities.Client _Client)
{
EFEntities.LookupClientStatu clientStatus;
var clientAddressList = new List<ClientAddress>();
if (_Client == null)
{
return;
}
//Assign data to client object
_Client.ClientName = rtxtName.Text;
_Client.Alias = rtxtAlias.Text;
_Client.ClientCode =Int32.Parse(rtxtClientCode.Text);
_Client.TaxPayerID = rtxtTaxPayerId.Text;
if (rcboStatus.SelectedIndex != 0)
{
clientStatus = new EFEntities.LookupClientStatu
{
ClientStatusID = (Guid) (rcboStatus.SelectedValue),
ClientStatusDescription = rcboStatus.Text
};
_Client.LookupClientStatu = clientStatus;
}
//_Client.Modified = EnvironmentClass.ModifiedUserInstance.Id;
_Client.EffectiveDate = rdtEffectiveDate.Value;
if (rdtExpDate.Value != rdtExpDate.MinDate)
{
_Client.ExpirationDate = rdtExpDate.Value;
}
else
{
_Client.ExpirationDate = null;
}
_Client.StartDate = DateTime.Now;
EFEntities.ClientAddress clientAddress = null;
// Iesi.Collections.Generic.ISet<ClientAddress> clientAddress = new HashedSet<ClientAddress>();
foreach (var cAddress in _clientController.client.ClientAddresses)
{
clientAddress = cAddress;
break;
}
if (clientAddress == null)
{
clientAddress = new EFEntities.ClientAddress();
}
clientAddress.Address1 = rtxtClientAdd1.Text;
clientAddress.Address2 = rtxtClientAdd2.Text;
clientAddress.Address3 = rtxtClientAdd3.Text;
// Address type details
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
clientAddress.City = rtxtClientCity.Text;
clientAddress.Client = _Client;
\
_Client.ClientAddresses.Add(clientAddress);
}
Well I did this to the following lines of code to make it work.
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
I changed the above code into this
if (rcboClientAddType.SelectedIndex != -1)
{
//clientAddress.LookupAddressType = new EFEntities.LookupAddressType
// {
// AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
// AddressTypeDescription = rcboClientAddType.Text
// };
clientAddress.AddressTypeID = (Guid)(rcboClientAddType.SelectedValue);
}
Hi everybody im starting to work with Entity Framework 4.0 and ASP.NET 4.0 i'm trying to make a master detail web page and i'm having problems when i try to add new items to a previously recorded items below is the i made for this:
private void guardarOrdenMedicamento()
{
InventarioSIAIplusEntities SIAplusContext = (InventarioSIAIplusEntities)(Session["context"]);
InvOrden orden;
string resultMessage;
if (DetalleMedicamentosOrden.Count == 0)
{
MessageBox1.ShowError("Debe especificar al menos un medicamento para la orden.");
return;
}
if (txtIDorden.Text.Trim() == "")
{
orden = new InvOrden();
orden.IDcentro = Convert.ToInt32(ddlCentros.SelectedValue);
orden.estado = ddlEstadoOrden.SelectedValue;
orden.fecha = Convert.ToDateTime(txtFechaCreacion.Text);
orden.comentario = txtComentarioOrden.Text;
orden.usuarioCrea = "Jeanc";
SIAplusContext.AddToInvOrdenes(orden);
resultMessage = "La orden fue registrada satisfactoriamente";
}
else
{
int idorden = Convert.ToInt32(txtIDorden.Text.Trim());
orden = SIAplusContext.InvOrdenes.Where(c => c.IDorden == idorden).First();
orden.estado = ddlEstadoOrden.SelectedValue;
orden.fecha = Convert.ToDateTime(txtFechaCreacion.Text);
orden.comentario = txtComentarioOrden.Text;
orden.usuarioCrea = "Jeanc";
resultMessage = "La orden fue actualizada satisfactoriamente";
foreach (var item in DetalleMedicamentosOrden)
{
if (item.IDorden == 0)
{
// item.IDorden = idorden;
// item.InvOrdenReference.EntityKey = orden.EntityKey;
//neww System.Data.EntityKey("InventarioSIAIplusEntities.InvOrdenes", "IDorden", orden.IDorden);
// SIAplusContext.AddToInvOrdenDets(item);
item.InvOrden = orden;
//
// SIAplusContext.AddToInvOrdenDets(item);
//orden.InvOrdenDets.Add(item);
}
else
{
InvOrdenDet det = SIAplusContext.InvOrdenDets.Where(c => c.IDorden == item.IDorden && c.IDmedicamento == item.IDmedicamento).First();
det.cantidadApr = item.cantidadApr;
det.cantidadSol = item.cantidadSol;
det.comentario = item.comentario;
}
}
}
SIAplusContext.SaveChanges();
}
The Error is :The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.
Thanks For any help with this.
I think that the problem is here:
item.InvOrden = orden;
You either have to use AddObject or update the values of an existing object.