In my "web store" mvc app I want to add items to database. Items table has CreatedBy field and it is a foreign key from User table UserId field. Everything was working before I put the database into the App_Data folder. Now I get the SqlException when trying to create a new Item:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Item_contains_User". The conflict occurred in database "C:\USERS\ALEKSEY\REPOS\2\WEBSTORE\WEBSTORE\APP_DATA\WEBSTORE.MDF", table "dbo.Users", column 'UserId'.
Here is the Create method of ItemRepository class:
public Item CreateItem(int productId, Guid userId)
{
var item = new Item
{
ProductId = productId,
CreatedBy = userId,
};
_dataContext.Items.InsertOnSubmit(item);
_dataContext.SubmitChanges(); // in this line the exception occures !
return item;
}
Here is the controller method Create:
[HttpGet]
public ViewResult Create()
{
var p = _productRepository.CreateProduct("", "", 0, "", "", "");
var userId = (Guid)Membership.GetUser().ProviderUserKey;
var item = _itemsRepository.CreateItem(p.ProductId, userId);
// some code
return View(model);
}
Besides, I use Linq to Sql model drag an' drop approach.
Here is the changed web.config connection string part:
<connectionStrings>
<add name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
As I said everything was working before I moved the database to App_Data file. I also tried to remove the dependency between Items and Users tables - the exact same exception.
Any help would be appropriate. Thanks in advance!
Edits:
Ok, now I really broke the dependency between Items and Users tables and no exception occures. But! I have to somehow know who has created each product, so breaking the dependency is not an option. I also tried to remove all code that initializes the CreatedBy field.
Any ideas??
Edits (part 2):
The second comment below gives a great advise! I found that all users that are created are stored now in the aspnet.sdf database!!!
But if I remove the connection string "DeafaultConnection":
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
I will get ConfigurationErrorsException:
"The connection name 'DefaultConnection' was not found in the applications
configuration or the connection string is empty."
in the folowing line:
var userId = (Guid)Membership.GetUser().ProviderUserKey;
Ok, as I guessed the issue was in the configuration. Each provider (for some reason) in the connection string had "DefaultConnection". I changed it to "WebStoreConnectionString". And now everything works!
p.s. thanks #w0lf, he pushed the thoughts in the right direction)
Related
i cant connect to sql 2012 in asp.net , c#
file: defalut.aspx -> page_Load
List<ozhatdata.tbl_diller> diller_result;
using (var ctx = new ozhatdata.bagDataContext())
{
diller_result = ozhatdata.DilIslemleri.GetAllLanguages(ctx);
}
int cnt = diller_result.Count ; // diller_result is null error
when i go to definition (F12) of the bagDataContext()
file: bag.designer.cs
public bagDataContext() :
base(global::ozhatdata.Properties.Settings.Default.ozhatprojeConnectionString15, mappingSource)
{
OnCreated();
}
when i go to definition (F12) of ozhatprojeConnectionString15
file: settings.designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute( "Data Source=.\\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;"+
"User ID=sa;Password=123; ")]
public string ozhatprojeConnectionString15 {
get {
return ((string)(this["ozhatprojeConnectionString15"]));
}
}
later i learned there is app.config file this line was present in app.config
<add name="Settings.ozhatprojeConnectionString15"
connectionString="Data Source=LIVE2RISE\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
i can connect to "user:sa pass:123" on "ms sql management studio"
!!!!error!!!!!!
System.NullReferenceException: Object reference not set to an instance of an object.
diller_result.count // this diller_result is null in debugger
line 36: for (int i = 0; i < diller_result.Count; i++)
Kaynak Dosya: c:\inetpub\wwwroot\site\Default.aspx.cs line : 36
im trying to figure out since yesterday.
please help me, thnks.
edit: after responce i tracked adn put a breakpoint
public static List<tbl_diller> GetAllLanguages(bagDataContext ctx = null)
{
try
{
//some stuf was here i deleted
}
catch (Exception ex)
{
string ms = ex.Message; // !!breakpoint
// the exception= coundt find stored procedure "dbo.getalllangs"
return null;
}
}
thank you. the problem is solved. it was caused by an evil try-cath duo.
i'll be more cautious with these "try catchs" from now on.
2nd time and Solution: this time eventhough i edit app.config, program uses old ConString from settings.designer.cs(i tracked it while debugging).
the program uses connString from setting.designer.cs too. app.config is not used/looked up/referred when Debugging
so we have to navigate in the solution>properties>settings.designer.cs edit connectionStrings there too.
i hope this helps anyone in future.
you can read this too:
Force regeneration of Settings.settings file after change in app.config
It seems that it is the call to ozhatdata.DilIslemleri.GetAllLanguagesthat did return a null value for diller_result.
You might want to check in that method what is causing it to return null.
I am using a web application where user pass one argument to the service and it will return string datatype which is query result. In the service i am using Entity Framework to query based on the user input but i am unable to get the data instead throwing an exception in my webapplication saying.....
The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Webapplication and service are two different solutions.
Code in My WCF service
public string GetFunctionality(string UserId)
{
string strRoleName = string.Empty;
objEntity = new SYMPHONY_TVEntities();
var Function = from t1 in objEntity.Users join t2 in objEntity.User_Role on t1.Role equals t2.User_Role1 where t1.UserID == UserId select t2;
var UserName = from it in objEntity.Users where it.UserID == UserId select it;
//Here i am getting exception
User_Role objRole = Function.First();
User objUser = UserName.First();
if (objRole.User_Function != null && objUser.User_Name != null)
{
strRoleName = objRole.User_Function + "$" + objUser.User_Name;
}
return strRoleName;
}
My connection string WCF service
<add name="SYMPHONY_TVEntities" connectionString="metadata=res://*/UsersModel.csdl|res://*/UsersModel.ssdl|res://*/UsersModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=inhi1u-hd0212\;Initial Catalog="SYMPHONY TV";Integrated Security=True;MultipleActiveResultSets=True'" providerName="System.Data.EntityClient" /></connectionStrings>
You code looks ok. The exception says it is unable to connect to the db. This means your connection string might be wrong, please verify your connection string. If this fails try adding this line of code after your objEntity. (Why?)
objEntity = new SYMPHONY_TVEntities();
objEntity.Connection.Open();
How do I retrieve both the Server Name and Database Name from a web.config connection string programatically through the .net api? Preferably without using an html or xml parser I create. Looking for the simplest way to retrieve this type of information.
Example web.config snippet:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnectionString" connectionString="Provider=SQLOLEDB;Data Source=MyServer;User ID=admind;password=ju7mpst#rterz_Fak3;Initial Catalog=dbDatabase" providerName="System.Data.OLEPlethora"/>
</connectionStrings>
<system.web>
result:
server=MyServer
database=dbDatabase
Found this link regarding retreiving connection string settings. This appears to be much simplier, however, I'm not sure if I can iterate over many connection string.
Get the connectionstring from config as such:
var myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
You can then use the oledb connectionstring builder to parse any connectionstring and extract the relevant parts.
var builder = new System.Data.OleDb.OleDbConnectionStringBuilder(myConnectionString);
var servername = builder["Data Source"];
var database = builder["Initial Catalog"];
Console.WriteLine("server={0}, database={1}", servername, database);
Good Day,
I have two connection strings defined in my web.config file.
<connectionStrings>
<add name="AppDb" connectionString="CONNECTION-STRING1"/>
<add name="LaptopDb" connectionString="CONNECTION-STRING2" />
</connectionStrings>
When I am working on my desktop, I want to use the connection string "AppDb". When I am working on my laptop, I want to use the connection string "LaptopDb". I don't want to comment out the line on the connection string everytime I work on a different machine.
I know that I can programatically do this. I'm just trying to figure out the best way.
Something like:
if (machineName == desktop)
use AppDb
else
use LaptopDb
but I don't like this approach. Is there something else I can test on?
Here's another couple of approaches you could consider:
You can use the configSource attribute to read the configuration for that element from another file, the contents of which can be different on each machine:
http://weblogs.asp.net/fmarguerie/archive/2007/04/26/using-configsource-to-split-configuration-files.aspx
Or you can use different build configurations and use XDT to transform the web.config file.
Really not too hard to do -- the trick is to use the System.Environment.MachineName to drive which string to pick and to get your connection string from a static property:
public static string ConnectionStringName
{
get
{
var customConnection = ConfigurationManager.ConnectionStrings[Environment.MachineName] != null;
var connectionStringName = customConnection ? Environment.MachineName : "DefaultDb";
return connectionStringName;
}
}
So I'm venturing out into the world of Linq and WCF web services and I can't seem to make the magic happen. I have a VERY basic WCF web service going and I can get my old SqlConnection calls to work and return a DataSet. But I can't/don't know how to get the Linq to SQL queries to work. I'm guessing it might be a permissions problem since I need to connect to the SQL Database with a specific set of credentials but I don't know how I can test if that is the issue. I've tried using both of these connection strings and neither seem to give me a different result.
<add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;User ID=domain\userName; Password=blahblah; Trusted_Connection=true"
providerName="System.Data.SqlClient" />
Here is the function in my service that does the query and I have the interface add the [OperationContract]
public string GetCity(int cityId)
{
GeoDataContext db = new GeoDataContext();
var city = from c in db.Cities
where c.CITY_ID == 30429
select c.DESCRIPTION;
return city.ToString();
}
The GeoData.dbml only has one simple table in it with a list of city id's and city names. I have also changed the "Serialization Mode" on the DataContext to "Unidirectional" which from what I've read needs to be done for WCF.
When I run the service I get this as the return: SELECT [t0].[DESCRIPTION] FROM [dbo].[Cities] AS [t0] WHERE [t0].[CITY_ID] = #p0
Dang, so as I'm writing this I realize that maybe my query is all messed up?
Try this:
public string GetCity(int cityId)
{
GeoDataContext db = new GeoDataContext();
var city = db.Cities.SingleOrDefault(c => c.CITY_ID == 30429);
return city.DESCRIPTION;
}
The problem with your query is that it's not returning a string in the var, it's returning an IQueryable. So when you ToString() the IQueryable, it must be returning a string representation of the SQL query represented by the IQueryable.