I'm having trouble with NHibernate, First let me say I'm not native English talker, OK, let get to point.
As i face this error, i searched over the internet, and saw lot of people talking about it, but most of them had issue with cascade attribute, and totally if i wanna say, non matched my case, or even if it did i couldn't get through.
My Database is so small, but a bit complex.
My model files generated using Entity Developer.
As you can see there is inheritance, one-to-many and many-to-many relation ships,
As I am new to NHibernate, i write a test code, my normal test worked, till i add this many-to-many relation ship.
So i write this code:
//Owner o = new Owner
//{
// //OwnerId = Guid.NewGuid(),
// CellPhone1 = null,
// CellPhone2 = "09132198895",
// Phone = "03114335502",
// Firstname = "Hassan",
// Lastname = "Faghihi",
// OwnerTitle = PersonTitle.Mr
//};
//OwnerFactory ownerFactory = new OwnerFactory();
//ownerFactory.SaveOwner(o);
//SellHouse sh = new SellHouse
//{
// //ItemId = Guid.NewGuid(),
// Owner = o,
// Address = "dsasd",
// BuildYear = 1393,
// City = "Isfahan",
// Code = "A-512",
// Country = "Iran",
// Description = "Nothing",
// Dimensions = "4X5",
// Directions = Directions.North | Directions.South,
// Document = "dasd",
// Exchange = true,
// Facilities = Facilities.Elevator | Facilities.KichenMdfService | Facilities.Parking | Facilities.Warehouse,
// Floor = 4,
// HasYard = false,
// HouseType = HouseType.Apartment,
// IssueDate = DateTime.Now,
// Loan = 3124,
// Meter = 130,
// NumberOfBlocks = 4,
// NumberOfFloors = 0,
// OtherFacilities = "Nothing",
// Rooms = 2,
// ShareOfSixPart = 4.2f,
// State = "Isfahan",
// District = "kaveh",
// ExchangeDescription = "",
// Images = null,
// IsRented = false,
// Maps = null,
// MortgagePayed = 0,
// Price = 2222222,
// RentAmount = 0,
// Substructure = 4,
//};
GalleryFactory galleryFactory = new GalleryFactory();
Gallery g = new Gallery
{
Image = Properties.Resources.jeans_texture03.ToByte()
};
galleryFactory.SaveGallery(g);
SellHouseFactory sellHouseFactory = new SellHouseFactory();
//factory.SaveSellHouse(sh);
HashSet<Gallery> galleries = new HashSet<Gallery>();
galleries.Add(g);
SellHouse sellHouse = sellHouseFactory.GetSellHouses().FirstOrDefault();
if (sellHouse != null)
{
comboBox1.SelectedIndex = (int)sellHouse.Owner.OwnerTitle;
textBox1.Text = sellHouse.Owner.Firstname+sellHouse.Owner.Lastname;
//sellHouse.Images = galleries;
sellHouseFactory.SaveSellHouse(sellHouse);
}
i create an object of Owner, then save it, and pass it to sellHouse, and set Images and Maps (which are my many-to-many relation) to null.
so the sellHouse Created.
then i was wonder how to add image or map to my sellHouse,
So i pass a list containing one gallery element to sellHouse Maps property.
And it generate "Illegal attempt to associate a collection with two open sessions", first i though the reason is because my Gallery didn't saved before i pass it to sell house, so i did as you can see on my code, and did it manually.
But it still keep on generating that error...
I provide required file so, you can set up an example and understand my code better.
I'm very eager to hear your answer,cause my hands are tied do to my little knowledge over Hibernate and NHibernate.
Sources in DropBox:
enter link description here
Probably in all of your factory method you open a new session.
But you have to open just one session in every thread (or transaction).
Related
I'm using Visual Studio to design a software that uses IBKR API to buy stocks. It's working fine if I'm buying integer stocks but I'm not able to buy fractional stocks.
I have found the function order.CashQty but it's not working.. this is the code that I'm using to buy, and it's working when I'm trying to buy integer stocks. Do you have any suggestion?
public void send_order(string side)
{
IBApi.Contract contract = new IBApi.Contract();
contract.Symbol = Global_variable.stock_sel;
contract.SecType = "STK";
contract.Exchange = cbMarket.Text;
contract.PrimaryExch = "ISLAND";
contract.Currency = "USD";
IBApi.Order order = new IBApi.Order();
order.OrderId = order_id;
order.Action = side;
order.OrderType = cbOrderType.Text;
//order.CashQty = 33.5; <-- maybe is this the way to buy fractionale share?
order.TotalQuantity = 1;
if (cbOrderType.Text == "STP")
{
order.AuxPrice = Convert.ToDouble(numPrice.Value);
}
order.DisplaySize = Convert.ToInt32(tbVisible.Text);
order.OutsideRth = chkOutside.Checked;
ibClient.ClientSocket.placeOrder(order_id, contract, order);
order_id++;
tbValid_Id.Text = Convert.ToString(order_id);
}
Thank you very much!
that code of my program, I hope that will help you:
private void buyStock(string symbol)
{
// Create a new contract to specify the security we are searching for
IBApi.Contract contract = new IBApi.Contract();
// Set the underlying stock symbol from the cbSymbol combobox
contract.Symbol = symbol.ToUpper();
// Set the Security type to STK for a Stock
contract.SecType = "STK";
// Use "SMART" as the general exchange
contract.Exchange = "SMART";
// Set the primary exchange (sometimes called Listing exchange)
// Use either NYSE or ISLAND
contract.PrimaryExch = "ISLAND";
// Set the currency to USD
contract.Currency = "USD";
IBApi.Order order = new IBApi.Order();
// gets the next order id from the text box
order.OrderId = order_id;
// gets the side of the order (BUY, or SELL)
order.Action = "BUY";
// gets order type from combobox market or limit order(MKT, or LMT)
order.OrderType = "MKT";
// number of shares from Quantity
order.TotalQuantity = 400;
// Value from limit price
//order.LmtPrice = Convert.ToDouble(numPrice.Text);
//
//Visible shares to the market
// order.DisplaySize = Convert.ToInt32(tbVisible.Text);
//order.OutsideRth = cbOutsideRTH.Checked;
//order.OutsideRth = chkOutside.Checked;
// Place the order
ibClient.ClientSocket.placeOrder(order_id, contract, order);
// increase the order id value
order_id++;
}
I am trying to directly charge the customer using Stripe. I am using this sample code:
var stripeChargeCreateOptions = new StripeChargeCreateOptions();
stripeChargeCreateOptions.Amount = 1000;
stripeChargeCreateOptions.Currency = "usd";
stripeChargeCreateOptions.Description = "Test";
stripeChargeCreateOptions.Source = new StripeSourceOptions()
{
Number = "4242424242424242",
ExpirationYear = "2022",
ExpirationMonth = "10",
AddressCountry = "US", // optional
AddressLine1 = "24 Beef Flank St", // optional
AddressLine2 = "Apt 24", // optional
AddressCity = "Biggie Smalls", // optional
AddressState = "NC", // optional
AddressZip = "27617", // optional
Name = "Joe Meatballs", // optional
Cvc = "1223" // optional
};
stripeChargeCreateOptions.Capture = true;
var stripeChargeService = new StripeChargeService();
StripeCharge stripeCharge = stripeChargeService.Create(stripeChargeCreateOptions);
This seems to work in test mode. Here are my 3 questions:
The amount 1000 here is 10 USD - right?
Will this also work using live keys? I heard Stripe does not allow direct charge and requires us to their Javascript and store token for us to actually charge? How is it working in test mode?
What is the importance of stripeChargeCreateOptions.Capture = true; What would happen if I set it to false?
Yes, that's right. All amounts are in cents/pence.
I don't know enough about Stripe to help you with this one I'm afraid.
This tells Stripe what process to use to carry out the transaction - it's the second half of a charge previously created with the Capture property set to 'false'. So you would later need to call the API with it set to true to actually complete the charge. See the API for more information: https://stripe.com/docs/api?lang=php#capture_charge
I have this very simple TPH Model.
When I add an object using context.TIImport.AddObject(tiObj)
and then call context.TIImport.Count() - the value doesn't include the new object?
I want to be able to add multiple objects before hitting context.SaveChanges()
var context = new CodeFirstContainer();
var g = new TIGuarantee
{
Id = 1,
AccountNumber = "123",
Amount = 123
};
context.TIImports.AddObject(g);
var il = new TIImportLoan
{
Id = 2,
AccountNumber = "123",
Amount = 123
};
context.TIImports.AddObject(il);
var i = context.TIImports.Count(); // = 0
context.SaveChanges();
var j = context.TIImports.Count(); // = 2
}
Is there any way to tell how many objects are in the collection WITHOUT calling SaveChanges?
You can do this by going into the ObjectContext.ObjectStateManager and check all entities with EntityState as Added to the right Collection and include that with your count. Why you want to do this however is not clear. When you perform a read, these entities wont be included untill you actually persist them to the underlying datastore with SaveChanges(); If your aim is not to make the changes final, maybe you should look into transactions then?
Actually I use DbContext, but I just tested it with ObjectContext as well.
// Engine 1
Engine engine = new Engine();
Manufacturer manufacturer = new Manufacturer();
engine.Manufacturer = manufacturer;
// Engine 2
engine = new Engine();
engine.Manufacturer = manufacturer // Engine 2 has the same manufacturer like Engine 1
context.SaveChanges();
I use identity columns (int), where new IDs are generated. In debug mode I see that the ID for engine is "0". Well, if I implement context.SaveChanges right after the Engine 1 block, the new manufacturer is being saved to DB. With EntityKey or Any check, I can reference the new manufacturer to Engine 2 without any problems. But without immediate SaveChanges(), two entries of same manufacturer are being saved to DB (the code above). Is EF unable to reference internally like normal objects? As you see above, manufacturer is one and the same object, so I wonder if it's possible to obtain a successfull insert without pre-save the child/manufacturer.
EDIT: I think I found the problem
MachineEntities context = new MachineEntities();
context.Configuration.AutoDetectChangesEnabled = true;
// Engine 1
Engine engine1 = new Engine();
engine1.Name = "engine1";
Manufacturer manufacturer = new Manufacturer();
manufacturer.Name = "manufacturer1";
engine1.Manufacturer = manufacturer;
// Engine 2
Engine engine2 = new Engine();
engine2.Name = "engine2";
manufacturer = new Manufacturer();
manufacturer.Name = "manufacturer1";
engine2.Manufacturer = manufacturer;
// Add Engine 1
if (context.Manufacturers.Any(m => m.Name == engine1.Manufacturer.Name))
{
// The manufacturer's name is identical, so use the one in the context instead the assigned one.
engine1.Manufacturer = context.Manufacturers.Single(m => m.Name == engine1.Manufacturer.Name);
}
else
{
// The manufacturer is not known, add it to the context
context.Set<Manufacturer>().Add(engine1.Manufacturer);
}
// Add Engine 2
if (context.Manufacturers.Any(m => m.Name == engine1.Manufacturer.Name))
{
// The manufacturer's name is identical, so use the one in the context instead the assigned one.
engine2.Manufacturer = context.Manufacturers.Single(m => m.Name == engine2.Manufacturer.Name);
}
else
{
context.Manufacturers.Add(engine2.Manufacturer);
}
context.SaveChanges();
context.Dispose();
"Any" or any comparison won't give me any results. It only gives me those entities, which are already persisted in DB, but not the fresh new added ones. So it's duplicated. The local ones are ignored as I see in debugger, and the one in "Result View" are the one, where the command is executed against. So the new added entities are located in "Manufacturers.Local".
I just tried the following:
var a1 = new Activity{WorkflowId = 1, Title = "test"};
var a2 = new Activity{WorkflowId = 1, Title = "test2"};
var d = new WorkflowDisplay{WorkflowId = 1, Title = "Test"};
a1.WorkflowDisplay = d;
a2.WorkflowDisplay = d;
// Any of the next three lines can be commented out, but if
// they are all commented, nothing happens.
AddToWorkflowDisplays(d);
AddToActivities(a1);
AddToActivities(a2);
SaveChanges();
... and I only saw a single WorkflowDisplay added. So I'm pretty sure this has something to do with your specific implementation. Have you overridden the GetHashCode or Equals methods of any of your entities, or done any similar sort of customization of the auto-generated code?
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.