In my project I've two Interesting database tables:
CREATE TABLE [dbo].[User]
(
[Id] INT NOT NULL IDENTITY,
[Name] NCHAR(60) NOT NULL,
PRIMARY KEY ([Id])
)
CREATE TABLE [dbo].[Event]
(
[Id] INT NOT NULL PRIMARY KEY identity,
...
[User id] INT NULL,
CONSTRAINT [FK_Event_User] FOREIGN KEY ([User id]) REFERENCES [User](Id)
)
I want to have access to the Event's users in my Application which take data from WCF.
To make this possible I've to change Child Property in User_Event Association according to this answer.
I use LINQ SQL and I noticed that event.User property is not null only when I invoke get properties on it.
Now I have to add for loop to force invoking this._User.Entity, but it don't look like this solution...
public List<Event> GetAllEvents()
{
var ev = Database.Instance.Db.Events;
foreach (var v in ev)
{
User u = v.User;
}
return ev.ToList();
}
Probably the problem was caused by DataContext.DeferredLoadingEnabled Property.
According to msdn:
DeferredLoadingEnabled
Gets or sets a value that indicates whether to delay-load one-to-many or one-to-one relationships.
update
finally I've solved this problem with LoadWith function from Linq to SQL.
db = new ModelDataContext();
/* setting lazy evaluation rules */
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith((Session s) => s.Exam);
dlo.LoadWith((Session s) => s.SessionUsers);
db.LoadOptions = dlo;
Related
I have a SQL table that has two foreign keys and when I run Entity Data Model Wizard and select Code First from database, and then create the tables, my table won't show up as a class. It generates something in the primary model class that looks like this:
modelBuilder.Entity<User>()
.HasMany(e => e.Categories)
.WithMany(e => e.Users)
.Map(m => m.ToTable("UserCategory").MapLeftKey("UserID").MapRightKey("ID"));
But I don't know how to use that to add or delete from that table, since it won't show up as a class when I'm coding.
My tables are:
CREATE TABLE [User]
(
ID NVARCHAR(128) PRIMARY KEY,
FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255),
JoinDate DATETIME,
ZipCode VARCHAR(25),
SearchRadius INT,
LoginToBusinessSide BIT
);
/*The categories businesses can fall under. */
CREATE TABLE Category
(
ID INT IDENTITY(1,1) PRIMARY KEY,
[Name] VARCHAR(255) UNIQUE NOT NULL,
);
/*The categories chosen by a specific user to get notified of*/
CREATE TABLE UserCategory
(
ID INT FOREIGN KEY REFERENCES Category(ID),
UserID NVARCHAR(128) FOREIGN KEY REFERENCES [User](ID),
CONSTRAINT PK_UserCategory PRIMARY KEY (ID, UserID)
);
How do I get UserCategory to show up as its own class, so I can easily access it?
I want to be able to just access it like every other class:
db.UserCategories.ID =
How can I
ADO doesn't create a class for my many to many table, but I can still access it. To add new categories to it, I use this code:
for(var i = 0; i < categories.Length; ++i)
{
var user = db.Users.Find(thisUser.ID);
var cat = db.Categories.Find(categories[i]);
user.Categories.Add(cat);
}
I have to an active connection to both tables that the foreign keys are linked to, and then when I add one to the Categories table, it goes to the correct place.
If you understand exactly why this works, or if there's a better way, please do comment.
For example, I have the following Table:
CustomerInfo
cus_id: auto increment, int, is Identity
cus_name: nvarchar
If I use the follow codes to insert the record "Peter",
string name = "Peter";
DataContext DC = new DataContext();
CustomerInfo newCustomer = new CustomerInfo();
newCustomer.cus_name = name;
DC.CustomerInfos.InsertOnSubmit(newCustomer);
DC.SubmitChanges();
The following error returns,
Can't perform Create, Update, or Delete operations on 'Table(CustomerInfo)' because it has no primary key.
Do I need to self-define the cus_id or any other solutions? Thanks!
First of all LINQ-To-SQL needs primary keys in order to be able to do Inserts and Updates, so you probably have to add the Primary Key in your table.
Now, because it is an auto incremented identity column, in your dbml, you have to select the column "cus_id" of the "CustomerInfo" table and go to the properties and set the following:
Auto Generated Value : True
Auto-Sync : OnInsert
This will ensure that when you insert a new row it will get a new id.
naratting from answer 1 of question you'll have to make cus_id as primary key too.
you can also try to do following
CREATE TABLE Customers
(
cus_id int NOT NULL AUTO_INCREMENT,
cus_name varchar(255) NOT NULL,
PRIMARY KEY (cus_id)
)
I got this error to. As far as I manged to fix it was to add a primary key.
This code made me a primary key and made it autoincrement. Maybe it's what you are looking for?
(When you create the table)
columnname bigint IDENTITY(1,1) NOT NULL,
CONSTRAINT pkcolumnname PRIMARY KEY CLUSTERED
I have simple table in Sybase
-- Creating table 'SimpleText'
CREATE TABLE [dbo].[SimpleText] (
[Id] nvarchar(10) NOT NULL,
[SimpleValue] nvarchar(120) NULL
);
GO
-- Creating primary key on [Id] in table 'SimpleText'
ALTER TABLE [dbo].[SimpleText]
ADD CONSTRAINT [PK_SimpleText]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
Based on this table it is created an model in entity framework (using 4.3).
Insert and delete is not a problem.
However when updating the table it generates an error when primary key is '[char][number]' i.e. a1 where it says that column a1 it not found.
By using a simple trace tool this is the sql generated :
update [dbo].[SimpleText]
set [SimpleValue] = :p0
where ([Id] = :p1)
and (Id = a1)
p0 = simpleTextValueUpdateda1
p1 = a1
Update code is as follow in C#:
using (var model = new Entities())
{
var entString = model.SimpleText.Select(t => t);
foreach (var simpleText in entString)
{
simpleText.SimpleValue = "simpleTextValueUpdated" + simpleText.Id;
}
model.SaveChanges();
}
There's not an issue if the same key is only a number.
Using SqlAnywhere12, EF4.3, C# on .NET 4
Has anyone experienced the same?
Is there a fix to ensure that text is apostrophed correctly in the sql?
It is confirmed that this issue was related to the version of the sybase sql/ef provider I was using.
The version 12.0.1.3726 generated this issue.
Download new EBF from sybase, 12.0.1.3742 and this specific issue should be resolved.
I've got an Entity Framework 4 model. There's 2 tables in that model, Subscribers and Versions:
CREATE TABLE tracking."Subscribers"
(
"SubscriberId" UUID NOT NULL,
"RemoteAddress" VARCHAR(80) NOT NULL,
"Priority" INTEGER NOT NULL DEFAULT 100,
"DataTypeId" INTEGER NOT NULL REFERENCES tracking."DataTypes" ( "DataTypeId" ),
"Condition" VARCHAR(8000),
"Version" BIGINT NOT NULL DEFAULT 0,
"LastConnected" TIMESTAMPTZ NOT NULL,
CONSTRAINT "Subscribers_pkey" PRIMARY KEY ("SubscriberId", "DataTypeId")
);
CREATE TABLE tracking."Versions"
(
"ObjectId" UUID NOT NULL,
"Source" UUID NULL,
"From" BIGINT NOT NULL,
"To" BIGINT NULL,
"DataTypeId" INTEGER NOT NULL REFERENCES tracking."DataTypes" ( "DataTypeId" ),
CONSTRAINT "Versions_pkey" PRIMARY KEY ("ObjectId", "DataTypeId")
);
Yes, there is a third table, DataTypes, but it's a lookup table & isn't important.
Also, you need to know that the values stored in the From & To columns in the Versions table represent version numbers. If the To column is not null, it means that the particular item represented by ObjectId has been deleted from the database.
In my C# code, I need to build a query. There is a Dictionary which contains one entry for each combination of data type ID & version number. I need to build a series of tests spearated by ORs, not ANDs.
Normally, to build the condition as a string for use in a DbCommand, I'd use code like this:
bool isFirst = true;
string query = "...";
foreach ( KeyValuePair<int, long> version in versionsLastSent ) {
if ( ! isFirst ) {
query += " OR ";
}
query += "....";
isFirst = false;
}
However, I don't know how to get that OR into the query using entity framework. I know that my query will be a generic IQueryable object and that I add conditions to it using
query = query.Where( a => ... );
But these are normally separated by ANDs. I need ORs.
How do I do this?
Tony
Edit:
I forgot to mention that the query needs to look like this when done:
SELECT *
FROM Versions
JOIN Subscribers . . .
WHERE <Some Condition> AND ( VersionCondition1 OR VersionCondition2 OR . . . )
The simplest way would be without OR, because you can get the exact same results using Union:
IQueryable originalQuery = ...;
IQueryable query = null;
foreach ( KeyValuePair<int, long> version in versionsLastSent ) {
IQueryable queryPart = originalQuery.Where(...);
if (query == null)
query = queryPart;
else
query = query.Union(queryPart);
}
Take a look at the PredicateBuilder.
http://www.albahari.com/nutshell/predicatebuilder.aspx
Basically you'd do something like this... (rough psuedo-code)
var predicate = new PredicateBuilder.False<YourType>();
if(someCondition)
{
predicate = predicate.Or(x=>x == newCondition);
}
query = context.where(predicate);
It's important to start with .False() if you're using OR to construct your query. This will give you a base evaluation to false that you can build on.
Is it possible to update a primary key after it's been created in SubSonic 3.0??
Consider this MySql table:
create table items (
Type varchar(30) NOT NULL,
Attribute varchar(30) NOT NULL PRIMARY KEY);
And I am trying to edit an item object (so called row)
item i = item.SingleOrDefault(i => i.Attribute == "123");
i.Attribute = "234";
i.Save();
The above snippet throws a syntax error MySQLException. After profiling the same, the query that was being executed at back end was this:
UPDATE ITEMS WHERE ATTRIBUTE="123";
Any suggestions/help please.