Error using entity framework to add rows to tables using foreign key relation - sql

I've written the following C# code:
abcEntities entities = new abcEntities();
abc_Lids_New newUserEntry = new abc_Lids_New()
{
Lid = lid,
FName = fname,
LName = lname,
Phone = phone,
};
newUserEntry.abc_class_Assignments_New = new System.Data.Objects.DataClasses.EntityCollection<abc_class_Assignments_New>();
foreach (string classId in classIds)
{
newUserEntry.abc_class_Assignments_New.Add(new abc_class_Assignments_New()
{
Lid = lid,
classID = classId
});
}
entities.abc_Lids_New.AddObject(newUserEntry);
entities.SaveChanges();
The code is supposed to add a new row in abc_Lids_New representing a new user. The code is also supposed to add rows in abc_class_assignments_new corresponding to the user's lid and a number of class ids.
However, I am getting an error: Unable to update the EntitySet 'UCV_TF_Assignments_New' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
Up until recently, I had only used the Entity Framework with stored procedures, so this is something new to me.

Your EntitySet "'UCV_TF_Assignments_New" is either based on a View (in which case, you have to create the InsertFunction (stored procedure)) or it lacks a Primary Key (in which case, add one).

Related

Unable to access table from alias name of column

Select name as id, code from the employee, The query is working perfectly on my database but when in spring boot I try to get the data from the table like:
Map namedQuery = (Map)iter.next();
namedQueryId = (String)namedQuery.get("namedQueryId");
for (iterator = rows.iterator(); iterator.hasNext();)
{
Map row = (Map)iterator.next();
Object code = row.get("code");
Object id = row.get("id");
}
id is always NULL in this while getting proper data in "code".
the name is being called using alias id so it is getting null values always

How do I map entity framework to a child-parent look up table based on a key

I have a database that has a parent-child look up for my drop down values, there is a domain table which represents what type of drop down it is ie "TITLE", "MARITAL_STATUS", "COUNTRY" and there is look up for the values associated with each of these drop downs that we call domain values
EG
TITLE (Domain table)
MR (Domain Value table)
MRS (Domain Value table)
MISS (Domain Value table)
DOCTOR (Domain Value table)
MARITAL_STATUS (Domain table)
SINGLE (Domain Value table)
MARRIED (Domain Value table)
DIVORCED (Domain Value table)
I find myself writing ugly code which exposes the under lying implementation similar to below
using (var db = new OrderContext())
{
...
var maritalStatusId = (
from sp in db.DomainValues
where sp.ShortCode == "MARRIED"
where sp.Domain.ShortCode == "MARITAL_STATUS"
select sp.Id
).FirstOrDefault();
if maritalStatusId != 0)
{
orderStore.maritalStatus = maritalStatusId;
}
...
db.OrderStores.Add(orderStore);
db.SaveChanges();
}
Is it possible to write code that looks similar to this
using (var db = new OrderContext())
{
...
orderStore.maritalStatus = new MaritalStatus { ShortCode = "MARRIED" }
...
db.OrderStores.Add(orderStore);
db.SaveChanges();
}
, where a navigation property handles the insert?
If so how do I set this up?
Any links to articles on this would be good too.
You can keep a cache with the different values of your dropdowns, that seems reasonnable, or you can use enumeration if the values are not dynamic.
Another solution would be to have the shortcode field to be the primary key of the table, all your problems would be resolved.

Insert Record into Table Join with LINQ-SQL ASP.NET MVC

Hi i would know how insert data into MsSQL DB using ASP.NET MVC.
I'm using (DBML) Entity with SQL-LINQ
I have 3 tables where 2 of them join with the first one
Table
User
id, name , surname , email
Car
id , id_User , model ,year
Work
id , id_User , location
I use this code to add a data into SQL
DataUserDataContext data = new DataUserDataContext();
User u = new User();
u.Name= "John";
u.Surname= "Lock";
u.email = "someemail#email.com"
data.Users.InsertOnSubmit(u);
p.SubmitChanges();
Now My question is :
How could insert a new record considering that i should fill Car and Work table too?
Use the code before and take the ID (if i wasnt wrong there is a way to get the last entity)
Use this id to insert record into Car and Work Table
Is there a way to do this in a unique step?
Don't think in terms of IDs but rather objects... put this code before SubmitChanges()...
u.Car = new Car() { model = 'honda', year = 2000 };
u.Work = new Work () { location = 'new york' };
first you can also use this to insert your data to the users table like this
DataUserDataContext data = new DataUserDataContext();
User u = new User();
u.Name= "John";
u.Surname= "Lock";
u.email = "someemail#email.com"
data.Users.AddObject(u)
data.SubmitChanges();
and you can get last inserted id from your Users table like this
var UserID= (from con in dbdata.Users
select con).Max(x => x.UserID);
and you can use to get last inserted id from users table
data.Users.OrderByDescending(u => u.UserId).FirstOrDefault()
and you can use this id to insert record from your car and work table like this
for Car table
DataUserDataContext data = new DataUserDataContext();
Car objcar = new Car()
objcar.id_User = UserID;
objcar.model="hondacity";
objcar.year="2012";
data.Cars.AddObject(objcar);
data.SubmitChanges();
for work table
DataUserDataContext data = new DataUserDataContext();
Work objwork=new Work();
objwork.id_User =UserID;
objwork.Location="US";
data.Works.AddObject(objwork);
data.SubmitChanges();
i think this will help you

linq to sql sub-select

I have two tables that represent say a Mixture and the components of the Mixture. The table layouts are like:
Mixture table:
MixtureID uniqueidentifier
MixtureDescription varchar(50)
Components table:
ComponentID uniqueidentifier
MixtureID uniqueidentifier (FK to previous table)
ComponentName varchar(50)
ComponentRatioPercentage int
Now, what I want to do is take a list of component names inputted from the user and find the ID's of any mixes that contain all of those components.
In SQL I could so something like:
select distinct MixtureID
from Mixture Mixture
where exists (select ComponentName
from Components Components1
where Components1.MixtureID = Mixture.MixtureID and
Components1.ComponentDescription = 'SomeComponentName')
and exists (select ComponentName
from Components2
where Components2.MixtureID = Mixture.MixtureID and
Components2.ComponentDescription = 'SomeOtherComponentName')
and exists....
etc, adding a sub-select for each component.
How would I do something like this in linq to sql? The number of components to look for would not be known in advance, until the user is done with input, though there would be a max of 10. Thanks in advance!
var components = new string[] {"SomeComponentName", "SomeOtherComponentName"};
var query = Mixtures.AsQueryable();
foreach (var component in components)
{
var tmpComponent = component;
query = query.Where(m => m.Components
.Any(c => t.ComponentDescription == tmpComponent)
);
}
var mixturesIds = query.Select(m=>m.MixtureId).Distinct();

NHibernate Linking Table with Data

SQL 2008 | .NET 4.0 | NHibernate 3.1 | NHibernate.Castle 3.1 | Castle.Core 2.5.2
So I have a linking table with metadata, like the author of this question NHibernate Mapping a Many to Many with Data on Join Table
Initially, I mapped just like the answer to this question as it seemed the most parsimonious way to handle it. However, after turning on show_sql and observing what was going on, the ID lookups ended up yielding N+1 queries where N is the number of associations.
Observe this example database that is analogous to my actual data, defined in sql-like syntax
CREATE TABLE [User]
(
Id int PRIMARY KEY
)
CREATE TABLE UserPref
(
Id int PRIMARY KEY,
Name varchar(32)
)
CREATE TABLE UserPrefAssociation
(
UserId int,
PrefId int,
Value varchar(32)
)
I hacked the following code together with this User one-to-many object mapping IList<UserPrefAssociation> Preferences { get; set; }
public IDictionary<string, string> GeneratePrefDict()
{
return Preferences
.ToDictionary(i => i.UserPref.Name, i => i.Value);
}
Sure, this works great, but as mentioned before, each i.UserPref.Name, is an additional query to SQL.
After playing in SQL, I have found the query that accomplishes what I want. My question then becomes how can I do this with NHibernate?
SELECT UserPref.Name, UserPrefAssociation.Value
FROM [User]
INNER JOIN UserPrefAssociation ON [User].Id = UserPrefAssociation.UserId
INNER JOIN UserPref ON UserPrefAssociation.UserPrefId = UserPref.Id
WHERE [User].Id = 1
~~~~SOLVED~~~~~
using NHibernate.Linq;
...
public IDictionary<string, string> GeneratePrefDict(ISession s)
{
return
(from entry in s.Query<User_UserPref>()
where entry.User == this
select new
{
key = entry.UserPref.Name,
value = entry.Value
})
.ToDictionary(i => i.key, i => i.value);
}
Generates this SQL
NHibernate: select userpref1_.Name as col_0_0_, user_userp0_.Value as col_1_0_ f
rom User_UserPref user_userp0_ left outer join UserPref userpref1_ on user_userp
0_.UserPrefId=userpref1_.Id where user_userp0_.UserId=#p0;#p0 = 1 [Type: Int32 (
0)]
Which is better than N+1 queries, and solves my issue.
I think you can achieve what you are wanting with Futures and QueryOver. Take a look at the following article:
Fighting cartesian product (x-join) when using NHibernate 3.0.0
If you can't visualize how to accomplish what you need from the above I can tailor that example more to your needs.