I have
User:
-ID
-Name
Badge
-ID
-Name (E.G "User has made 100 posts", the same relationship as Stackoverflow)
So I've realised I need a third table, (as badges are defined in the DB aswell so I've created:
UserBadge
-ID
-User
-Badge
So now in my User class I have
List<UserBadge> Badges;
Problem is, I'm going
Users.Find(1).Badges.Where(x => x.User == user && x.Badge = badgeIWant)
.FirstOrDefault();
(Or something similar) Because... EF doesn't have the intelligence (I'm guessing) to automatically know that "Badges" should only include the ones where the User matches.
How should I do this? Was thinking I could have a custom getter for Badges, that has that LINQ conditional in it...
This is EF 4.3 code first:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace ConsoleApp
{
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Badge> Badges { get; set; }
}
public class Badge
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class Context : DbContext
{
public Context()
: base("Votes")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Badge> Badge { get; set; }
}
class Program
{
static void Main(string[] args)
{
Context context = new Context();
User user = context.Users.Include("Badges").Where(u => u.ID == 1).SingleOrDefault();
if(user != null)
{
//write your code.
}
Console.ReadKey();
}
}
}
I've tested it and this should work. This would typically be a many to many relationship because User can have many badges and 1 badge can belong to many users. If you run this code, you will find EF creates BadgeUsers table with BadgeID and UserID as foreign keys. From there on you can query and EF knows which badges you talking about.
If you want to get all the badges of the user then just use users.Find(1).Badges. EF will automatically filter the badges related to the user.
Related
I have a simple POCO type, say something like
public class OwnedEntity {
public string stringProperty { get; set; }
public decimal decimalProperty { get; set; }
public bool boolProperty { get; set; }
public int intProperty { get; set; }
}
and an actual entity with an OwnedEntity reference
public class SomeEntity {
public string Id { get; set; }
public OwnedEntity OwnedEntity { get; set; }
}
I set up the relationship like described in the documentation using EF Core's Fluent API:
protected override void OnModelCreating (ModelBuilder builder) {
base.OnModelCreating (builder);
builder.Entity<SomeEntity> ().OwnsOne (e => e.OwnedEntity);
}
I can't find anything on how to define default-values for all the properties of OwnedEntity. I tried to initialize the properties like this:
public class OwnedEntity {
public string stringProperty { get; set; } = "initial"
public decimal decimalProperty { get; set; } = -1M;
public bool boolProperty { get; set; } = false;
public int intProperty { get; set; } = -1;
}
but with no effect. Same goes with the [DefaultValueAttribute] (but that was to expect since it's explicitly mentioned).
There's a bit of information on how to handle initial values for regular entities:
modelBuilder.Entity<SomeOtherEntity>()
.Property(e => e.SomeIntProperty)
.HasDefaultValue(3);
But since I'm facing an Owned Entity Type, I can't access the type via Entity<T>.
Is there a way of doing what I'm looking for?
Some things worth mentioning:
I have a solid amount of specific entities where most of them are using the OwnsOne relation
Declaring all OwnedEntity-properties in a base class is not an option since not all the entities have those properties
I`m using EF Core 2.0.3 and ASP.NET Core MVC 2.0.4
Edit:
Originally, I wanted to have newly created SomeEntity instances to come with preset properties for all of the 'embedded' SomeEntity.OwnedEntity properties.
But looking at how my associated controller works, it all makes sense... I have the following methods for the 'Create' operation:
[HttpGet]
public IActionResult Create () {
return View (nameof (Create));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create (SomeEntity model) {
context.Add (model);
await context.SaveChangesAsync ();
// redirect etc.
}
Which means that no object is created for the [HttGet] overload of Create and all the HTML inputs linked to properties (via asp-for) are initially empty. Okay. So I guess the proper way of doing this is to manually create a new instance of SomeEntity and pass it to the Create view like this:
[HttpGet]
public IActionResult Create () {
return View (nameof (Create), new SomeEntity());
}
Is this the right approach then or are there some more things to keep in mind?
Assuming you understand what EF Core Default Values are for, and just looking for equivalent of Entity<T>().Property(...) equivalent.
The owned entities are always configured for each owner type by using the ReferenceOwnershipBuilder<TEntity,TRelatedEntity> class methods. To access this class you either use the result of OwnsOne method, or use the OwnsOne overload taking second argument of type Action<ReferenceOwnershipBuilder<TEntity,TRelatedEntity>>.
For instance, using the second approach:
builder.Entity<SomeEntity>().OwnsOne(e => e.OwnedEntity, ob =>
{
ob.Property(e => e.stringProperty)
.HasDefaultValue("initial");
ob.Property(e => e.decimalProperty)
.HasDefaultValue(-1M);
// etc.
});
I'm new to Xamarin forms and am up to the point where I now want to be persisting data entered by the user to an Sqlite db. Thankfully, there all plenty of examples to get you started, but thats as far as the help goes... I'm trying to implement a relationship between two entities 'Session' and 'HandHistory'.
A Session can have multiple HandHistories - immediately I saw that some sort of foreign key would be needed here to link these tables/entities together. I read in multiple articles and stack overflow questions that the standard 'sqlite-net-pcl' (by Frank A.Krueger) package offers nothing in terms of foreign keys, and that in order to acquire the functionality I needed to use the SQLiteNetExtensions library. I referred to this article for help:
https://bitbucket.org/twincoders/sqlite-net-extensions/overview
My entities look like this:
Session:
using SQLite;
using SQLiteNetExtensions.Attributes;
namespace PokerSession.Models
{
[Table("Session")]
[AddINotifyPropertyChangedInterface]
public class Session
{
public Session(bool newSession)
{
if (newSession)
{
CurrentlyActive = true;
//HandHistories = new ObservableCollection<HandHistory>();
}
}
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public SessionType SessionType { get; set; } = SessionType.Tournament;
public string Location { get; set; }
public DateTime Date { get; set; } = DateTime.Now;
public string GeneralNotes { get; set; }
public int MoneyIn { get; set; }
public int MoneyOut { get; set; }
public int ProfitLoss
{
get
{
var p = MoneyOut - MoneyIn;
if (p < 0)
return 0;
return p;
}
}
/// <summary>
/// If the session has not been completed, set this to true
/// </summary>
public bool CurrentlyActive { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public ObservableCollection<HandHistory> HandHistories { get; set; }
}
}
HandHistory:
using SQLite;
using SQLiteNetExtensions.Attributes;
namespace PokerSession.HandHistories
{
[Table("HandHistory")]
[AddINotifyPropertyChangedInterface]
public class HandHistory
{
public HandHistory()
{
}
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Session))]
public int SessionId { get; set; }
[ManyToOne]
public Session Session { get; set; }
}
}
I also followed this article for the platform specific implementations for obtaining the SQLiteConnection for the local db:
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/databases/
The error I'm getting:
'SQLiteConnection' does not contain a definition for 'UpdateWithChildren' and the best extension method overload 'WriteOperations.UpdateWithChildren(SQLiteConnection, object)' requires a receiver of type 'SQLiteConnection' PokerSession.Android, PokerSession.iOS C:\Poker Notes Live\PokerSession\PokerSession\PokerSession\Services\DataService.cs 46 Active
private SQLiteConnection _database;
public DataService()
{
_database = DependencyService.Get<ISqLite>().GetConnection();
_database.GetTableInfo("HandHistory");
_database.CreateTable<Session>();
_database.CreateTable<HandHistory>();
var session = new Session(false)
{
Location = "Test Location",
Date = new DateTime(2017, 08, 26),
MoneyIn = 35,
MoneyOut = 0,
SessionType = SessionType.Tournament,
GeneralNotes = "blah blah"
};
var hh = new HandHistory();
_database.Insert(session);
_database.Insert(hh);
session.HandHistories = new ObservableCollection<HandHistory> {hh};
_database.UpdateWithChildren(session);
}
So basically it's not allowing me to use the SQLite Extension methods with my SQLiteConnection object (_database) which is confusing as this is the whole point behind the Extension methods? Surely they're made to work with the SQLiteConnection object?? I've also noticed through my playing around that there seems to be two different types of SQLiteConnection... The one I'm currently using is in the 'SQLite' namespace, and another one in the SQLite.Net namespace. I have checked the one in the SQLite.Net namespace and it does seem to like the Extension methods but it requires me to change my platform specific implementation for obtaining the SQLiteConnection, but it would fail at runtime (complaining about my Session entity not having a PK??).
Quite a long winded question I know but it's better to provide more information than not enough, and I'm sure there must be others experiencing similar problems so please comment and offer any help possible, thank you.
using the latest (current) RC1 of asp.net5 I'm looking at creating a simple relationship between a User entity and a WorkLog entity.
Is it possible to use the ApplicationUser Class from Identity as a starting point and use the ApplicationUser key which is defined as the linking key? I have had problems extending the ApplicationUser in the past and therefore generated a seperate dbcontext (pointing to the same database) and created my own plumbing in order to pass the IdentityUsers Id into my seperate dbcontext. Does anyone have any examples of extending the IdentityDbContext adding foreign key tables mapping to the IdentityUser Class?
Example below
//DBContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<WorkLogItem> WorkLogItems { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<WorkLogItem>(
e =>
{
e.Property(p => p.id).IsRequired().UseSqlServerIdentityColumn();
});
}
}
//WorkLogItem
public class WorkLogItem
{
public int id { get; set;}
public String UserId { get; set; }
public int Hours { get; set; }
public String Description { get; set; }
}
//ApplicationUser
public class ApplicationUser : IdentityUser
{
public ICollection<WorkLogItem> WorkLogItems { get; set; }
}
Doing what you've asked is expected to work out of the box. You can look at this commit to see the difference between a newly created MVC 6 project with Identity and your schema above.
Registering a user, and refreshing /Home/Index causes WorkLogItems to be added as expected. Note you don't need a separate DB context for this.
public IActionResult Index()
{
var user = _db.Users.Include(p => p.WorkLogItems).FirstOrDefault();
if (user != null)
{
user.WorkLogItems.Add(new WorkLogItem { Description = "New item added" });
_db.SaveChanges();
ViewBag.WorkItems = user.WorkLogItems.ToList();
}
else ViewBag.WorkItems = new WorkLogItem[] { };
return View();
}
The key items to be aware of when you add any collection to an existing entity are;
Make sure you add the migration and update the databse
Make sure you use Include on the query because EF7 does not support Lazy Loading.
I would like to set up a many to many relationship in ASP.NET MVC4.
The goal is to extend the default UserProfile class with a list of Timeline objects, which belong to the user.
A Timeline could be shared by multiple users, so the Timeline class should have an list of UserProfile objects aswell.
Timeline class:
namespace MvcApplication1.Models
{
public class Timeline
{
public int Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public List<UserProfile> Users { get; set; }
}
public class TimelineContext : DbContext
{
public DbSet<Timeline> Timelines { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
// Added the following because I saw it on:
// http://www.codeproject.com/Tips/548945/Generating-Many-to-Many-Relation-in-MVC4-using-Ent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Timeline>()
.HasMany(c => c.Users)
.WithMany(s => s.Timelines)
.Map(mc =>
{
mc.ToTable("TimelineOwners");
mc.MapLeftKey("TimelineId");
mc.MapRightKey("UserId");
});
}
}
}
UserProfile class (default class with an added property):
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Timeline> Timelines { get; set; }
// Added the following because I saw it on:
// http://www.codeproject.com/Tips/548945/Generating-Many-to-Many-Relation-in-MVC4-using-Ent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserProfile>()
.HasMany(c => c.Timelines)
.WithMany(s => s.Users)
.Map (mc =>
{
mc.ToTable("TimelineOwners");
mc.MapLeftKey("UserId");
mc.MapRightKey("TimelineId");
});
}
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public List<Timeline> Timelines { get; set; }
}
I have a connection table with foreign keys:
When creating an instance of Timeline, the Users list is null:
Timeline timeline = db.Timelines.Find(id); // timeline.Users = null
Can somebody please enlighten me, how should I set this up working?
I'm totally new to ASP.NET MVC4.
Edit 1: I understand I should not extend UserProfile but create another class to store users. Once the many-to-many relationship works, I will refactor and go into that direction.
But first I would like to know why is it not working.
Edit 2:
The double context also caused problems, two databases were created for the two contexts and the pure join table was empty in one of them.
I suggest that you work through this article about the options how you can load navigation properties with Entity Framework. This is very basic knowledge which is important for every kind of relationship, not only many-to-many relationships.
Looking at that article you will find then that this line...
Timeline timeline = db.Timelines.Find(id);
...does not load any related entities. So, it's expected that timeline.Users is null, even if the entities are related in the database.
If you want to load the Users you can use eager loading:
Timeline timeline = db.Timelines.Include(t => t.Users)
.SingleOrDefault(t => t.Id == id);
This is a single database query. Or to enable lazy loading you have to mark your navigation properties as virtual:
public virtual List<UserProfile> Users { get; set; }
//...
public virtual List<Timeline> Timelines { get; set; }
You can then use your original code:
Timeline timeline = db.Timelines.Find(id); // first query
var users = timeline.Users; // second query
This will run two separate queries. The second is performed as soon as you access the navigation property for the first time.
BTW: Is there a reason why you have two context classes - TimelineContext and UsersContext? "Normally" you need only one context.
I'm not a fan of messing with the working of the internal userprofile. I would suggest creating your own user class, linking it to the simplemembershipprovider and adding functionality there. At max you'll extend the accountclasses a little to add more fields to register with, but that's about it.
Follow this extremely handy guide to get things working and let me know if you encounter an error.
I've just installed the new Entity Framework 4.1 NuGet package, thus replacing the EFCodeFirst package as per NuGet intructions and this article of Scott Hanselman.
Now, imagine the following model:
public class User
{
[Key]
public string UserName { get; set; }
// whatever
}
public class UserThing
{
public int ID { get; set; }
public virtual User User { get; set; }
// whatever
}
The last EFCodeFirst release generated a foreign key in the UserThing table called UserUserName.
After installing the new release and running I get the following error:
Invalid column name 'User_UserName'
Which of course means that the new release has a different FK naming strategy. This is consistent among all other tables and columns: whatever FK EFCodeFirst named AnyOldForeignKeyID EF 4.1 wants to call AnyOldForeignKey_ID (note the underscore).
I don't mind naming the FK's with an underscore, but in this case it means having to either unnecessarily throw away the database and recreate it or unnecessarily renaming al FK's.
Does any one know why the FK naming convention has changed and whether it can be configured without using the Fluent API?
Unfortunately, one of the things that didn't make it to this release is the ability to add custom conventions in Code First:
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-release-candidate-available.aspx
If you don't want to use the fluent API to configure the column name (which I don't blame you), then most straight forward way to do it is probably using sp_rename.
Why don't you do the following?
public class User
{
[Key]
public string UserName { get; set; }
// whatever
}
public class UserThing
{
public int ID { get; set; }
public string UserUserName { get; set; }
[ForeignKey("UserUserName")]
public virtual User User { get; set; }
// whatever
}
Or, if you don't want to add the UserUserName property to UserThing, then use the fluent API, like so:
// class User same as in question
// class UserThing same as in question
public class MyContext : DbContext
{
public MyContext()
: base("MyCeDb") { }
public DbSet<User> Users { get; set; }
public DbSet<UserThing> UserThings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserThing>()
.HasOptional(ut => ut.User) // See if HasRequired fits your model better
.WithMany().Map(u => u.MapKey("UserUserName"));
}
}