I have Estate and Contract tables. Estate table has Boolean property (Available). When clients are confirms their contract Available property in Estate table changing its value to false. Estate selects from combobox by EstateID. Problem is that I don’t know how to get access to Available property by ID selected in EstateCombobox.
contract.ContractDate = Convert.ToDateTime(ContractDateTextBox.Text);
contract.OperationType = OperationTypeComboBox.SelectedItem.ToString();
contract.Description = DescriptionTextBox.Text;
contract.EstateID = Convert.ToInt32(EstateComboBox.SelectedValue);
contract.ClientID = Convert.ToInt32(ClientComboBox.SelectedValue);
contract.EmployeeID = Convert.ToInt32(EmployeeComboBox.SelectedValue);
contract.NewOwnerID = Convert.ToInt32(NewClientOwnerComboBox.SelectedValue)
EstateComboBox.DataSource = AgencyContext.Estate.ToList();
EstateComboBox.DisplayMember = "EstateName";
EstateComboBox.ValueMember = "EstateID";
EstateComboBox.Invalidate();
I hope I understand you correctly:
int eid = Convert.ToInt32(EstateComboBox.SelectedValue.ToString());
var myEstate = AgencyContext.Estate.Single(e => e.EstateID == eid);
myEstate.Available = false; //new value
dbcontext.SaveChanges();
Related
I built an ASP.net usercontrol and I am trying to get the text from the checkbox to pass to the database. My problem is I keep getting an error on submission with the method I use. Here is what I used:
ResidenceHallInspection rhi = new ResidenceHallInspection();
rhi.versionId = version.id;
rhi.submitDate = DateTime.Now;
rhi.CheckInOrOut = ddlCheck.SelectedItem.Text;
rhi.StudentId = txtStudentId.Text;
rhi.FirstName = txtFirstName.Text;
rhi.MiddleName = txtMiddleName.Text;
rhi.LastName = txtLastName.Text;
rhi.Walls = chbxWalls.SelectedItem.Text;
rhi.Windows = chbxWindows.SelectedItem.Text;
rhi.Blinds = chbxBlinds.SelectedItem.Text;
rhi.Couch = chbxCouch.SelectedItem.Text;
rhi.CommonRoomCouch = chbxCRCouch.SelectedItem.Text;
rhi.CommonRoomChair = chbxCRChair.SelectedItem.Text;
rhi.Doors = chbxDoors.SelectedItem.Text;
rhi.Carpet = chbxCarpet.SelectedItem.Text;
rhi.Ceiling = chbxCeiling.SelectedItem.Text;
rhi.CommonRoomCounter = chbxCRCounter.SelectedItem.Text;
rhi.Cabinet = chbxCabinet.SelectedItem.Text;
rhi.Phone = chbxPhone.SelectedItem.Text;
rhi.Bed = chbxBed.SelectedItem.Text;
rhi.Desk = chbxDesk.SelectedItem.Text;
rhi.DeskChairs = chbxDeskChair.SelectedItem.Text;
rhi.Tub = chbxTub.SelectedItem.Text;
rhi.Vanity = chbxVanity.SelectedItem.Text;
rhi.Notes = txtNotes.Text;
rhi.Building = txtResHall.Text;
rhi.ApartmentNumber = txtSuitNo.Text;
rhi.BedSpace = txtBedSpace.Text;
house.AddToResidenceHallInspections(rhi);
house.SaveChanges()
It would be good to see more information, such as the error you received, and possible the code and/or HTML for the custom user control. However, there are a couple of possibilities which seem likely. One is that your SelectedItem property may be null, which would cause an ObjectReferenceException to occur. Another is that Text itself is null, and that your database doesn't allow a null value for one or more of the fields you're assigning.
You can get a better answer than this rather vague one if you provide more information.
I have 2 tables in the database carrier and vendor. vendor has a foreign key of Carrier_Id. When the user want add a vendor, the user will select a carrier from a combobox where the valve from carrier table.
The problem I facing now is that,I don't know how to get the valve from combobox so that I can insert it into the database.
I use this code to get valve from carrier table to show in the combobox.
MyinvoiceDataDataContext contect = new MyinvoiceDataDataContext();
var st = from s in contect.Carriers
select new { s.CarrierID, s.CarrierName};
comVendorCarrier.ItemsSource = st;
comVendorCarrier.DisplayMemberPath = "CarrierName";
comVendorCarrier.SelectedValuePath = "CarrierID";
To get the value of this combobox (i.e. the selected carrier), all you need is just use the two properties SelectedValue to get the CarrierId or SelectedText to get the value (i.e. CarrierName).
For example, you could get the id of the selected carrier by using:
int SelectedCarrierId = int.parse(comVendorCarrier.SelectedValue.ToString());
Or if you need the CarrierName you should use:
string CarrierName = comVendorCarrier.SelectedText;
Edit: Assuming that your tables have the following structre:
Carrier:
CarrierId.
CarrierName.
Vendor:
VendorId.
CarrierId: a foreign key references Carriers(CarrierId).
VendorName.
These two tables should be mapped in your .dbml file to two entities Vendor and Carrier, in which the Vendor class has a property of type Carrier that represents the foreign key CarrierID.
Then in order to view CarrierName in the vendors list, you can do this:
var vendorsList = _db.Vendors
.Select( vendor => new
{
VendorId = vendor.Id,
VendorName = vendor.Name,
CarrierName = vendor.Carrier.Name
});
using (MyinvoiceDataDataContext connv = new MyinvoiceDataDataContext())
{
Vendor editven = (from s in connv.Vendors
where s.VendorID == vendor.VendorID
select s).FirstOrDefault();
editven.VendorAddress = editven.VendorAddress;
editven.VendorBalance = editven.VendorBalance;
editven.VendorContactName = editven.VendorContactName;
editven.VendorEmail = editven.VendorEmail;
editven.VendorFax = editven.VendorFax;
editven.VendorName = editven.VendorName;
editven.VendorPaymentTerms = editven.VendorPaymentTerms;
editven.VendorPhone = editven.VendorPhone;
editven.VendorRemark = editven.VendorRemark;
editven.VendorTax = editven.VendorTax;
editven.VendorWebsite = editven.VendorWebsite;
editven.CarrierID = editven.CarrierID;
connv.SubmitChanges();
}
I'm having trouble performing an update in the Entity Framework. I don't really understand the behaviour I am seeing.
I am using the AdventureWorks database.
The starting value for the StateProvince is Micronesia. If I change it to Maryland, the update is successful. However, if I then try to change it back to Micronesia, I get the following error:
"Cannot insert duplicate key row in object 'Sales.SalesTerritory' with
unique index 'AK_SalesTerritory_Name'.\r\nThe statement has been
terminated."
The DAL method in question is:
public static void UpdateCustomer(CustomerDetails customerDetails)
{
AWEntities context = Common.GetContext();
var customerQuery = from c in context.Individuals
.Include("Contact")
.Include("Customer.CustomerAddresses.Address.StateProvince.SalesTerritory")
//.Include("Customer.SalesTerritory.StateProvinces")
.Where(id => id.CustomerID == customerDetails.CustomerId)
select c;
var individual = customerQuery.ToList().ElementAt(0);
Contact contact = individual.Contact;
contact.LastName = customerDetails.LastName;
contact.MiddleName = customerDetails.MiddleName;
contact.FirstName = customerDetails.FirstName;
contact.EmailAddress = customerDetails.EmailAddress;
contact.Phone = customerDetails.Phone;
contact.Title = customerDetails.Title;
AWModel.Customer customer = individual.Customer;
customer.CustomerID = customerDetails.CustomerId;
customer.SalesTerritory.Name = customerDetails.SalesTerritory;
Address address = individual.Customer.CustomerAddresses.ElementAt(0).Address;
address.AddressLine1 = customerDetails.AddressLine1;
address.AddressLine2 = customerDetails.AddressLine2;
address.City = customerDetails.City;
address.PostalCode = customerDetails.PostalCode;
address.StateProvinceID = customerDetails.SalesProvinceId;
context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
}
Can anyone identify the correct way to do what I am attempting.
This is occurring when you update the SalesTerritory.Name property:
customer.SalesTerritory.Name = customerDetails.SalesTerritory;
The effect is to change the SalesTerritory entity, rather than the customer entity. I believe you want something more like:
customer.SalesTerritoryID = customerDetails.SalesTerritoryID;
This code cause double record...
i checked my insert code for all tables and it works fine...
and this is insert code:
StoreDO store = new StoreDO();
List<BrandDO> brandList = new BrandBL().SelectBrands();
StoreBL storeBL = new StoreBL();
store.StoreName = txtStoreName.Text;
store.StorePhone = txtStorePhone.Text;
store.StoreAddress = txtStoreAddress.Text;
store.CityID = int.Parse(ddlCity.SelectedValue);
store.CountyID = int.Parse(ddlCounty.SelectedValue);
store.IsActive = chkIsActive.Checked;
int storeID = storeBL.InsertStore(store);
ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
for (int i = 0; i < brandList.Count; i++) {
string brandName = brandList[i].BrandName.ToString() + brandList[i].BrandID.ToString();
StoreBrandBL storeBrandBL = new StoreBrandBL();
CheckBox chkBrand = (CheckBox)contentPlaceHolder.FindControl(brandName);
if (chkBrand != null) {
if (chkBrand.Checked) {
StoreBrandDO storeBrandDO = new StoreBrandDO();
storeBrandDO.StoreID = storeID;
storeBrandDO.BrandID = brandList[i].BrandID;
storeBrandDO.IsActive = true;
storeBrandBL.InsertStoreBrand(storeBrandDO);
}
}
}
Duplicating rows in your database should be avoided in the code and protected against in the database.
As hwcverwe said you can use table constraints but you should also try to set the primary key correctly for each table.
If you are using surrogate keys on all tables (such as the StoreID and BrandID I see in your code) then you will have to use unique table constraints to prevent duplicate data. Configuring your database correctly will also show up the problem areas in your code as the database will throw an exception when an insert fails.
EDIT: In response to your comment your question title is incorrect if you are asking about CheckBox controls.
Looking at the code it appears you are trying to find a checkbox control in a ContentPlaceholder but you do not show the code which creates the checkboxes.
Hey. Nooby question but new with Entity.
I am trying to create a new user object and some details in some additional tables which have a foreign key of the newly created user id.
I've attempted to do this in one round trip. Do I have to add the user to the database first and then go back, set the userid's on the other objects and add them. Here is the Entity Model and code to elaborate:
using (var context = new ServicesEntities())
{
newUser = new UsersTable();
newUser.Address = user.UserDetails.Address;
newUser.City = user.UserDetails.City;
newUser.Country = user.UserDetails.Country;
newUser.Email = user.Email.EmailString;
newUser.FirstName = user.UserDetails.FirstName;
newUser.LastName = user.UserDetails.LastName;
newUser.State = user.UserDetails.State;
newUser.Zip = user.UserDetails.Zip;
context.UsersTables.AddObject(newUser);
context.SaveChanges();
}
using (var context = new ServicesEntities())
{
var referralDetails = new UserReferrals();
referralDetails.CreatedThruServiceId = 1; // todo don't make this an absolute 1
referralDetails.ReferralEmail = user.ReferralDetails.ReferralEmail;
referralDetails.TwoPlusTwoHandle = user.ReferralDetails.TwoPlusTwoHandle;
referralDetails.UserId = newUser.UserId;
context.UserReferrals.AddObject(referralDetails);
context.SaveChanges(); // THIS WORKS FINE!
}
using (var context = new ServicesEntities())
{
var credentials = new UserCredentials();
credentials.CreatedOn = DateTime.Now;
credentials.EmailValidated = false;
//credentials.EmailValidatedOn = null;
credentials.FailedLoginAttempts = 0;
credentials.IsLockedOut = false;
//credentials.LastValidLogin = null;
credentials.Password = user.Password.PasswordString;
credentials.PermissionId = 1; // todo don't make this an absolute 1 = user
credentials.SuccessfulLoginAttempts = 0;
credentials.UserId = newUser.UserId; ;
context.UserCredentials.AddObject(credentials);
context.SaveChanges(); // THIS ONE CRAPS OUT!
}
When I run this I get the following Exception when I run SaveChanges():
{"A dependent property in a
ReferentialConstraint is mapped to a
store-generated column. Column:
'UserId'."}
Note: Updated this with some slightly different code based on an example in a book.
Note2: I've narrowed down the problem to be in the adding of credentials.
Note3: Fixed this, I accidentally had AUTO-INCREMENT set on my UserCredentials userid. If anyone ares here is working code:
public POCO.User AddNewUserToDb(User user)
{
if (IsDuplicateUser(user.Email.EmailString))
{
throw new DuplicateNameException("This email is already taken.");
}
UsersTable newUser;
using (var context = new ServicesEntities())
{
newUser = new UsersTable();
newUser.Address = user.UserDetails.Address;
newUser.City = user.UserDetails.City;
newUser.Country = user.UserDetails.Country;
newUser.Email = user.Email.EmailString;
newUser.FirstName = user.UserDetails.FirstName;
newUser.LastName = user.UserDetails.LastName;
newUser.State = user.UserDetails.State;
newUser.Zip = user.UserDetails.Zip;
var referralDetails = new UserReferrals();
referralDetails.CreatedThruServiceId = 1; // todo don't make this an absolute 1
referralDetails.ReferralEmail = user.ReferralDetails.ReferralEmail;
referralDetails.TwoPlusTwoHandle = user.ReferralDetails.TwoPlusTwoHandle;
//referralDetails.UserId = newUser.UserId;
var credentials = new UserCredentials();
credentials.CreatedOn = DateTime.Now;
credentials.EmailValidated = false;
//credentials.EmailValidatedOn = null;
credentials.FailedLoginAttempts = 0;
credentials.IsLockedOut = false;
//credentials.LastValidLogin = null;
credentials.Password = user.Password.PasswordString;
credentials.PermissionId = 1; // todo don't make this an absolute 1 = user
credentials.SuccessfulLoginAttempts = 0;
//credentials.UserId = newUser.UserId; ;
newUser.Credentials = credentials;
newUser.ReferralDetails = referralDetails;
context.UsersTables.AddObject(newUser);
context.SaveChanges();
}
user.UserId = newUser.UserId;
return user;
Try to add related records directly to UserTable record:
newUser.Credentials.Add(credentials);
newUser.ReferralDetails.Add(referralDetails);
Do not set any Id. It will be set during saving automatically.
Edit: Btw. make sure that UserId column in UserCredentials table is not set as auto generated in database.
Take a look at these links:
Using the entity framework to add existing entities to a collection on a newly created entity.
How to create foreign key relationships with the Entity Framework?
Entity Framework - insert new object with a collection of existing objects
The key links for EF4:
Fortunately, in EF4 we can directly
update the relationship due to the
Foreign Key Association which allows
us to keep the foreign key property
inside the entity classes. For
detail, please see
http://blogs.msdn.com/adonet/archive/2009/11/06/foreign-key-relationships-in-the-entity-framework.aspx.
Besides, we have another great feature
Self Tracing Entities, which makes the
n-tier pattern much easier in EF,
http://blogs.msdn.com/adonet/archive/2009/11/15/updated-feature-ctp-walkthrough-self-tracking-entities-for-the-entity-framework.aspx.
EF4 will allow you to include the foreign key values as scalar properties of your entities. Make sure the "Include foreign keys" checkbox is checked when you create your EDM.
Looking at your model, it looks like you've already done that. Just set the foreign key values explicitly, no need to do a round trip.