Linq making primary key system.nullable<int> not just int - linq

I'm mapping my database into base object with Linq to SQL. I drag all the tables into my dbml and they all setup nicely. I save the dbml and it creates the classes that represent the tables, etc.
In my database I have a table as such:
CREATE TABLE [dbo].[BidNames](
[BidNameID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NOT NULL,
[BidName] [varchar](75) NOT NULL,
CONSTRAINT [PK_BidNames] PRIMARY KEY CLUSTERED
(
[BidNameID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
The BidNameID field is clearly a primary key and obviously NOT NULL. Linq, however defines BidNameID like this:
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_BidNameID", DbType="Int")]
public System.Nullable<int> BidNameID
{
get
{
return this._BidNameID;
}
set
{
if ((this._BidNameID != value))
{
if (this._BidName1.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnBidNameIDChanging(value);
this.SendPropertyChanging();
this._BidNameID = value;
this.SendPropertyChanged("BidNameID");
this.OnBidNameIDChanged();
}
}
}
Where BidNameID is defined as System.Nullable. All the other tables in my database resolve correctly so I'm left wondering why this is happening. Any ideas?
Thanks in advance.
EDIT
I have discovered that this problem is related to another table. If I drop the Bids table from my dbml and re-save, the BidNameID column correctly resolves to int. If I put the Bids table back and save it goes back to Nullable. The Bids table has a foreign key into the BidNames table but the data is clean. Here is the structure of the Bids table:
CREATE TABLE [dbo].[Bids](
[BidID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NOT NULL,
[ItemID] [int] NOT NULL,
[Amount] [money] NOT NULL,
[BidName] [varchar](75) NOT NULL,
[BidTime] [datetime] NOT NULL,
[BidNameID] [int] NULL,
CONSTRAINT [PK_Bids] PRIMARY KEY CLUSTERED
(
[BidID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_BidNames] FOREIGN KEY([BidNameID])
REFERENCES [dbo].[BidNames] ([BidNameID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_BidNames]
GO
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_Customers] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[Customers] ([CustomerID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_Customers]
GO
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_Items] FOREIGN KEY([ItemID])
REFERENCES [dbo].[Items] ([ItemID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_Items]
GO

I took your table script, ran in my DB and dragged it into a dbml and it didn't generate as nullable (VS2010, VB.NET 4.0):
<Global.System.Data.Linq.Mapping.ColumnAttribute(
Storage:="_BidNameID", AutoSync:=AutoSync.OnInsert,
DbType:="Int NOT NULL IDENTITY", IsPrimaryKey:=True,
IsDbGenerated:=True)>
Public Property BidNameID() As Integer
Get
Return Me._BidNameID
End Get
Set(value As Integer)
If ((Me._BidNameID = value) _
= False) Then
Me.OnBidNameIDChanging(value)
Me.SendPropertyChanging()
Me._BidNameID = value
Me.SendPropertyChanged("BidNameID")
Me.OnBidNameIDChanged()
End If
End Set
End Property
Maybe try one or more of these?
drop/recreate the physical table
delete/recreate your DB connection in Server Explorer
delete/recreate the dbml
manually edit the designer file
create additional datacontext partial class and manually maintain that table/mapping

I don't necessarily understand why but when I alter the Bids table and make the BidNameID field NOT NULL, it fixes the problem with the BidName.BidNameID field. It now resolves to int rather than nullable.

Related

How to make Identity use of MVC instead of razor pages in asp.net core 2.2

Since asp.net core 2.1 the MVC is not supported as default model with Identity. I want to run Identity with MVC in asp.net core 2.2
Make a long story short. This is a asp.net 4.6.2 site with local db that I want upgrade to asp.net core 2.2 . I thought that this would be simple thing. So wrong I was. So what did I do:
Created an new ASP.net core 2.0 project with local Identity
Scaffolded the ef context with database first with Scaffold-DbContext
Fixed so EF is loaded correctly in Startup.
Removed aspnetusers, aspnetuserroles, aspnetuserlogin, aspnetroles models from generated scaffold by the Scaffold-Dbcontext
Updated ApplicationDbContext to inherits from IdentityDbContext. ApplicationUser inherits from IdentityUser
After I faked that the migration have been applied, I manually added following columns in aspnetusers
6.1 ConcurrencyStamp
6.2 NormalizedUserName
6.3 NormalizedEmail
6.4 Changed name LockoutEnd? to LockoutEnd
The system builds but still I cant get it to use the Account controller. I have followed the steps in https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2
without no avail. It seems what I do I can't get it to read the mvc controller even after I scaffolded the Identity.
I think the difference in implementations of Identity in asp.net core 2.X Identity is either to high or to narrow regarding earlier implementations.
Included part of my startup
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
// services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
//options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
//options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Account/Login";
options.LogoutPath = $"/Account/Logout";
options.AccessDeniedPath = $"/Account/AccessDenied";
});
// using Microsoft.AspNetCore.Identity.UI.Services;
services.AddSingleton<IEmailSender, EmailSender>();
}
I want to use MVC with Identity Core 2.2 with an old database from Identity .Net.
So any suggestions?
It's not clear what you're doing exactly, but it sounds like you've scaffolded the Identity Razor Pages into your project. If that's the case, those are going to take precedent over your controller, since it's a more physical route.
All the other code looks good. You're using AddIdentity instead of AddDefaultIdentity (so the default UI is not included). Assuming you've actually created an AccountController and your routing is set up correctly, then it should work, as long as you don't have the default UI physically scaffolded into your project.
Recently I have done the same thing. The following might help you. First create equivalent Application tables for all AspNet tables. The MS SQL Server script below will create:
dbo.ApplicationRole
dbo.ApplicationRoleClaim
dbo.ApplicationUser
dbo.ApplicationUserClaim
dbo.ApplicationUserLogin
dbo.ApplicationUserRole
dbo.ApplicationUserToken
Open MS SQL Server Management Studio
Select your database
Start a new query
Run the script below and replace YOUR_DATABASE with the name of your database
Next you should copy the contents of your soon obsolete AspNet tables into the new Application tables. In this process you should also handle the change from datatype nvarchar to int for UserId and RoleId.
USE [YOUR_DATABASE]
GO
/****** Object: Table [dbo].[ApplicationRole] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationRole](
[Id] [int] NOT NULL,
[Name] [nvarchar](256) NULL,
[NormalizedName] [nvarchar](256) NULL,
[ConcurrencyStamp] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationRoles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationRoleClaim] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationRoleClaim](
[Id] [int] IDENTITY(1,1) NOT NULL,
[RoleId] [int] NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationRoleClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUser] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUser](
[Id] [int] NOT NULL,
[UserName] [nvarchar](256) NULL,
[NormalizedUserName] [nvarchar](256) NULL,
[Email] [nvarchar](256) NULL,
[NormalizedEmail] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[ConcurrencyStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEnd] [datetimeoffset](7) NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
CONSTRAINT [PK_ApplicationUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserClaim] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserClaim](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationUserClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserLogin] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserLogin](
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[ProviderDisplayName] [nvarchar](max) NULL,
[UserId] [int] NOT NULL,
CONSTRAINT [PK_ApplicationUserLogins] PRIMARY KEY CLUSTERED
(
[LoginProvider] ASC,
[ProviderKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserRole] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserRole](
[UserId] [int] NOT NULL,
[RoleId] [int] NOT NULL,
CONSTRAINT [PK_ApplicationUserRole] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserToken] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserToken](
[UserId] [int] NOT NULL,
[LoginProvider] [nvarchar](128) NOT NULL,
[Name] [nvarchar](128) NOT NULL,
[Value] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationUserTokens] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[LoginProvider] ASC,
[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[ApplicationRoleClaim] WITH CHECK ADD CONSTRAINT [FK_ApplicationRoleClaims_ApplicationRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[ApplicationRole] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationRoleClaim] CHECK CONSTRAINT [FK_ApplicationRoleClaims_ApplicationRoles_RoleId]
GO
ALTER TABLE [dbo].[ApplicationUser] WITH CHECK ADD CONSTRAINT [FK_ApplicationUsers_Club] FOREIGN KEY([ClubId])
REFERENCES [dbo].[Club] ([Id])
GO
ALTER TABLE [dbo].[ApplicationUser] CHECK CONSTRAINT [FK_ApplicationUsers_Club]
GO
ALTER TABLE [dbo].[ApplicationUserClaim] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserClaims_ApplicationUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserClaim] CHECK CONSTRAINT [FK_ApplicationUserClaims_ApplicationUsers_UserId]
GO
ALTER TABLE [dbo].[ApplicationUserLogin] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserLogins_ApplicationUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserLogin] CHECK CONSTRAINT [FK_ApplicationUserLogins_ApplicationUsers_UserId]
GO
ALTER TABLE [dbo].[ApplicationUserRole] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserRole_ApplicationRole] FOREIGN KEY([RoleId])
REFERENCES [dbo].[ApplicationRole] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserRole] CHECK CONSTRAINT [FK_ApplicationUserRole_ApplicationRole]
GO
ALTER TABLE [dbo].[ApplicationUserRole] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserRole_ApplicationUser] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserRole] CHECK CONSTRAINT [FK_ApplicationUserRole_ApplicationUser]
GO
ALTER TABLE [dbo].[ApplicationUserToken] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserTokens_ApplicationUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserToken] CHECK CONSTRAINT [FK_ApplicationUserTokens_ApplicationUsers_UserId]
GO

refreshing generated code from dbml

I've added two new tables to the database.
I've dropped them on the design surface.
My understanding is that it should just automatically generate the design.cs code as a result.
It did, according to my faulty memory, when I added a new table last week, but not this week.
I checked the references in csproj and everything looks OK there.
I tried the RunCustomTool, but that didn't seem to pull anything in to either the DBML or the designer.cs.
No combination of deleting, saving, and re-adding has had any effect.
This is using the MSLinqToSQLGenerator, not SQLMetal
It feels like there is some simple trick I'm missing.
UPDATE: So the problem is with a specific table.
If I add this table, it generates correctly.
CREATE TABLE [dbo].[_LeakageClass](
[id] [int] NOT NULL,
[Class] [nvarchar](25) NOT NULL,
[Description] [nvarchar](50) NOT NULL
CONSTRAINT [PK__LeakageClass] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
If I add this table, it quits working and nothing else generates code from then on.
CREATE TABLE [dbo].[_SeatSize](
[model] [int] NOT NULL,
[ValveSize] [int] NOT NULL,
[SeatSize] [int] NOT NULL,
[Stroke] [int] NOT NULL
CONSTRAINT [PK__SeatSize] PRIMARY KEY CLUSTERED
(
[model] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
It couldn't handle having a field named similar to the table.
CREATE TABLE [dbo].[_SeatSize](
[SeatSize] [int] NOT NULL,
doesn't work.
CREATE TABLE [dbo].[_SeatSize](
[SeatSizer] [int] NOT NULL,
works fine. Note that the underscore prefix on the table isn't enough to make a difference.

updating create view - error ORA-01779:

I've used the CREATE VIEW command to create a view (obviously), and join multiple tables. The CREATE VIEW command works perfectly, but when I try to update the VIEW RentalInfoOct, I receive error "ORA-01779: cannot modify a column which maps to a non key-preserved table"
CREATE VIEW RentalInfoOct
(branch_no, branch_name, customer_no, customer_name, item_no, rental_date)
AS
SELECT i.branchNo, b.branchName, r.customerNo, c.customerName, i.itemNo, r.dateFrom
FROM item i
INNER JOIN rental r
ON i.itemNo = r.itemNo
INNER JOIN branch b
ON i.branchNo = b.branchNo
INNER JOIN customer c
ON r.customerNo = c.customerNo
WHERE r.dateFrom
BETWEEN to_date('10-01-2009','MM-DD-YYYY')
AND to_date('10-31-2009','MM-DD-YYYY')
My update command.
UPDATE RentalInfoOct
SET item_no = '3'
WHERE customer_name = 'April Alister'
AND branch_name = 'Kingsway'
AND rental_date = '10/28/2009'
I'm not sure if this will help in solving the problem, but here are my CREATE TABLE commands
CREATE TABLE Branch
(
branchNo SMALLINT NOT NULL,
branchName VARCHAR(20) NOT NULL,
branchAddress VARCHAR(40) NOT NULL,
PRIMARY KEY (BranchNo)
);
--Item Table Definition
CREATE TABLE Item
(
branchNo SMALLINT NOT NULL,
itemNo SMALLINT NOT NULL,
itemSize VARCHAR(8) NOT NULL,
price DECIMAL(6,2) NOT NULL,
PRIMARY KEY (ItemNo, BranchNo),
FOREIGN KEY (BranchNo) REFERENCES Branch ON DELETE CASCADE,
CONSTRAINT VALIDAMT
CHECK (price > 0)
);
-- Customer Table Definition
CREATE TABLE Customer
(
customerNo SMALLINT NOT NULL,
customerName VARCHAR(15) NOT NULL,
customerAddress VARCHAR(40) NOT NULL,
customerTel VARCHAR(10),
PRIMARY KEY (CustomerNo)
);
-- Rental Table Definition
CREATE TABLE Rental
(
branchNo SMALLINT NOT NULL,
customerNo SMALLINT NOT NULL,
dateFrom DATE NOT NULL,
dateTo DATE,
itemNo SMALLINT NOT NULL,
PRIMARY KEY (BranchNo, CustomerNo, dateFrom),
FOREIGN KEY (BranchNo) REFERENCES Branch(BranchNo) ON DELETE CASCADE,
FOREIGN KEY (CustomerNo) REFERENCES Customer(CustomerNo) ON DELETE CASCADE,
CONSTRAINT CORRECTDATES CHECK (dateTo > dateFrom OR dateTo IS NULL)
);
See: Oracle: multiple table updates => ORA-01779: cannot modify a column which maps to a non key-preserved table
You're attempting to update a view with joins, but the join conditions are not based on a uniqueness constraint, which creates the possibility of multiple rows that are created from a single row in one table.
It seems like you need a Unique Key - Foreign Key relationship between the columns your join condition is based on.
EDIT: I just saw your edit. Changing r.branchNo = b.branchNo to i.branchNo = b.branchNo should go a long way. Not sure how well r.customerNo = c.customerNo will work out.

LINQ query in EF - many to many and a cross join

A simple stored procedure that I want to handle with LINQ instead:
SELECT
CASE WHEN mg.MovieID IS NULL THEN 0 else 1 end as Selected ,
g.genreID, g.GenreName
FROM dbo.Genres g LEFT JOIN
(
SELECT MovieID, GenreID FROM [dbo].[MovieGenre] m
WHERE m.MovieID = #Movie
) MG
ON g.[GenreID] = mg.[GenreID]
ORDER BY g.GenreName
I think this should be simple and I think it would be a common requirement, yet I can't figure it out nor have I found a solution via searching the web.
The app is in WPF backed by an EF model. Since EF hides the join table I need LINQ syntax that can deal with the absence of the intermediary table.
Classic many-to-many with a simple join table: table 1:Movies, table 2: Genres, Join table: MovieGenres. In the UI the user selects a specfic movie. For that movie I want to bring back ALL the genres and a bool value indicating whether the genre has been assigned to the movie. Hours of attempting this in LINQ have failed me, so the solution is currently to have the stored procedure above generate the values for me. I won't always be abe to do this with a stored procedure and would love to see a LINQ solution.
Here's the actual SQL table structures
CREATE TABLE [dbo].[Genres](
[GenreID] [int] IDENTITY(1,1) NOT NULL,
[GenreName] [nvarchar](15) NOT NULL,
CONSTRAINT [PK_Genres] PRIMARY KEY CLUSTERED
(
[GenreID] ASC
)) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Movies](
[MovieID] [int] IDENTITY(1,1) NOT NULL,
[MovieTitle] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Movies] PRIMARY KEY CLUSTERED
(
[MovieID] ASC
))
ON [PRIMARY]
GO
CREATE TABLE [dbo].[MovieGenre](
[MovieID] [int] NOT NULL,
[GenreID] [int] NOT NULL,
CONSTRAINT [PK_MovieGenre] PRIMARY KEY CLUSTERED
(
[MovieID] ASC,
[GenreID] ASC
)) ON [PRIMARY]
GO
ALTER TABLE [dbo].[MovieGenre] WITH CHECK ADD CONSTRAINT [FK_Genres] FOREIGN KEY([GenreID])
REFERENCES [dbo].[Genres] ([GenreID])
GO
ALTER TABLE [dbo].[MovieGenre] CHECK CONSTRAINT [FK_Genres]
GO
ALTER TABLE [dbo].[MovieGenre] WITH CHECK ADD CONSTRAINT [FK_Movies] FOREIGN KEY([MovieID])
REFERENCES [dbo].[Movies] ([MovieID])
GO
ALTER TABLE [dbo].[MovieGenre] CHECK CONSTRAINT [FK_Movies]
GO
This should do the trick.
use from and in with the navigation property for a join
DefaultIfEmpty to make it a left join
Using a ternary operator ? : for the case statement
Query:
var query = from g in context.Genres
from m in g.Movies.Where(x => x.MovieID == movieId)
.DefaultIfEmpty()
orderby g.GenreName
select new {
Selected = m == null ? 0 : 1,
g.genreID,
g.GenreName
};

Mapping an entity to more than one table (EF4, WCF RiaServices) - Internationalization

if I understood several other posts correctly it's currently not possible to map an entity to more than one table if they do not share the same primary key.
Is this still true? What I'm wondering is how internationalization should be handled with the db design below and EF.
I've a internationalized db where texts are stored in separate tables.
e.g.
CREATE TABLE Product(
ProductID int IDENTITY(1,1) NOT NULL,
ProductGroupID int NOT NULL,
...
CONSTRAINT PK_Product PRIMARY KEY CLUSTERED
(
ProductID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY
) ON PRIMARY
CREATE TABLE Product_i18n(
ProductID int NOT NULL,
LanguageID int NOT NULL,
ProductName nvarchar(150) NULL,
Description nvarchar(max) NULL,
...
CONSTRAINT PK_Product_i18n PRIMARY KEY CLUSTERED
(
ProductID ASC,
LanguageID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY
) ON PRIMARY
So the product consists of two tables. In the table Product the language independent part is stored and in the table Product_i18n the language dependend part is stored.
The two tables are physically linked with a 1:n association, but logically it's a 1:1 association because I always need one language at a certain operation.
Therefore I would like to combine the two tables in a single entity Product which consists of the columns
ProductID
ProductGroupID
LanguageID
ProductName
Description ...
If this would be possible I could keep the internationalized table out of my model to make it more clear.
Is this possible with EF4. Any guidance and experiences with internationalization to solve this issue are welcome.
Thanks a lot
Uwe
I don't know if you are still having the problem, but you can solve it using a view for your products, more accurate, one view for each language.

Resources