c#


can't make EF work with my existing DB


I have this 4 tables on my database, i am trying to retrieve which fleets are assigned to a user which session is open and also the selected fleet.
dbo.UserAccount
UserID (PK,uniqueidentifier,not null)
PrimaryFleet (FK,uniqueidentifier,not null)
SelectedFleet(FK,uniqueidentifier,not null)
the UserAccount table has 2 FK, which both point to the column dbo.Fleets.OwnerID
dbo.Session
SessionID (PK,uniqueidentifier,not null)
UserID (FK,uniqueidentifier,not null)
the Session table has a FK pointing to dbo.UserAccount.UserID
dbo.UserFleet
UserID (FK,uniqueidentifier,not null)
OwnerID (FK,uniqueidentifier,not null)
UserFleet is just a table to know which fleets are assigned to each user, so its a many to many relation
dbo.Fleets
OwnerId (PK,uniqueidentifier,not null)
ownerName (nvarchar(255),not null)
I am trying with the following code. which works correctly except that my var fleets returns empty, i don't know how to tell entity framework how to relate dbo.UserAccount with dbo.Fleets via the table UserFleet.
if (HttpContext.Session["Session"] == null)
{
return null;
}
var response = new getchangesModel();
var session = new Guid(HttpContext.Session["Session"].ToString());
using(Dal.DbContext dc = new Dal.DbContext())
{
var SessionSet = dc.Sessions.Where(S => S.SessionID == session).Include(d => d.UserAccount).SingleOrDefault();
var SelectedFleet = dc.Fleets.Where(f => f.OwnerId == SessionSet.UserAccount.SelectedFleet).SingleOrDefault();
var fleets = dc.UserAccounts.Where(u => u.UserID == SessionSet.UserAccount.UserID).Include(f => f.Fleet);
}
This is my models definition
[Table("Session")]
public class Session
{
[Key]
public Guid SessionID { get; set; }
public Guid UserID { get; set; }
public virtual UserAccount UserAccount { get; set; }
}
[Table("Fleets")]
public class Fleet
{
[Key]
public Guid OwnerId { get; set; }
public String ownerName { get; set; }
public virtual ICollection<UserAccount> UserAccount { get; set; }
}
[Table("UserAccount")]
public class UserAccount
{
[Key]
[Display(Name="UserID")]
public Guid UserID { get; set; }
public Guid SelectedFleet { get; set; }
public Guid? PrimaryFleet { get; set; }
public virtual Fleet Fleet { get; set; }
public virtual ICollection<Session> Session { get; set; }
}
EF does not know what column PrimaryFleet or SecondaryFleet is related to your property Feet. You can specify this:
modelBuilder.Entity<UserAccount>()
.HasRequired(a => a.Fleet)
.WithMany(a => a.UserAccount)
.HasForeignKey(a => a.SelectedFleet);
or
modelBuilder.Entity<UserAccount>()
.HasOptional(a => a.Fleet)
.WithMany(a => a.UserAccount)
.HasForeignKey(a => a.PrimaryFleet);
Previous answer.
According your database design, tables UserAccount and Fleets have many-to-many relationship (via UserFleet table). But your classes design means that UserAccount can have only one Fleet. So, at first replace
public virtual Fleet Fleet { get; set; }
to
public virtual ICollection<Fleet> Fleets { get; set; }
and at second add the following code to OnModelCreating method of your DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserAccount>()
.HasMany<Fleet>(s => s.Fleets)
.WithMany(c => c.UserAccounts) // i renamed your Fleet.UserAccount property to UserAccounts to show that it is collection
.Map(cs =>
{
cs.MapLeftKey("UserID");
cs.MapRightKey("OwnerID");
cs.ToTable("UserFleet");
});
}

Related Links

c# how to take data_type as input in “foreach” clause
Combine path from a list of objects
Confusion about directory tree
Windows Runtime app Encrypt sqlite database and synchronization
How to use group by on an outer join in linq to SQL
How to setup IIS or WCF service for access to local resources
Inserting into MySQL database from C# Webforms, give ArgumentException
Flatten a nested object to map its properties to the target object
Get all inherited classes of a generic abstract class
Display System.Windows.Forms.DataGridView new Record row at the top instead of bottom?
Converting jagged array to 2D array C#
How to convert php->json to c# class?
Binding DependencyProperty to non-DependencyProperty
Getting Error An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter
Using async/await with pre-defined delegate signature
Why does MessageQueue.Send(Object) NOT work when sending to remote private queue using FormatName?

Categories

HOME
asp.net
autohotkey
url
ldap
wifi
ibm
query-string
ms-application-insights
swap
servicenow
install
sitemap
genexus
samsung-gear-s2
core-data
facebook-sharer
hdf5
browsermob
box2d
loss
multibinding
geography
legend-properties
passbook
caldav
url-parameters
typedef
prepros
advertising
ps
jira-zephyr
suitescript
sasl
android-cursorloader
gulp-jshint
workflow-foundation
scripting-language
hierarchy
recreate
2checkout
jboss-arquillian
multilanguage
log4net-configuration
minitest
mkdir
libconfig
motion
armadillo
aspose.pdf
collation
f#-fake
ack
automapper-4
pyopenssl
dynamic-linking
photoshop-script
htop
petapoco
dynatable
spring-cloud-aws
huawei
sharing
stringbuilder
ownership
consolidation
strtol
falcon
sprockets
angularfire
diameter-protocol
kik
phpdesigner
custom-build-step
calc
magnet-uri
jcomponent
event-tracking
lytro
android-togglebutton
pdcurses
cl.exe
teamstudio-unplugged
nsnotificationcenter
powerpoint-2010
sendy
yandex-api
opencobol
windows-phone-store
xtify
grape-api
zend-db-table
violation
record-locking
mandelbrot
dd4t
outlook-object-model
coinbase-php
database-restore
nsregularexpression
netbiscuits
blackberry-eclipse-plugin
nude.js
joomla1.7
jqzoom
flexbuilder
soapexception
windows-xp-embedded
sipdroid
jquery-attributes
linq-to-mysql
large-data-volumes
disk-based

Resources

Encrypt Message