I got two models, a User and a Team as below:
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId _id { get; set; }
[Display(Name = "Password:")]
public string Password { get; set; }
[Display(Name = "Confirm:")]
public string ConfirmPassword { get; set; }
[Display(Name = "Email:")]
public string Email { get; set; }
[Display(Name = "Username:")]
public string UserName { get; set; }
[Display(Name = "Firtname:")]
public string Firstname { get; set; }
[Display(Name = "Lastname:")]
public string Lastname { get; set; }
[Display(Name = "Country:")]
public string Country { get; set; }
[Display(Name = "City:")]
public string City { get; set; }
[Display(Name = "Birthdate:")]
public int Birthdate { get; set; }
public List<Team> Teams { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId TeamID { get; set; }
public string TeamName { get; set; }
public string UserName { get; set; }
public int LeagueID { get; set; }
public List<Player> Player { get; set; }
So I've created a user but now I want to add teams to my user.
This is the code I'm using:
var databaseClient = new MongoClient(Settings.Default.FantasySportsConnectionString);
var server = databaseClient.GetServer();
var database = server.GetDatabase("Users");
var collection = database.GetCollection<User>("users");
var user = collection.AsQueryable().First(o => o._id == Session["ID"]);
user.Teams.Add(new Team { TeamID = new ObjectId(), TeamName = "Some Team" });
But when I do this I get these errors:
1: Instance argument: cannot convert from 'MongoDB.Driver.MongoCollection<SportsFantasy_2._0.Models.User>' to 'System.Collections.IEnumerable'
2: 'MongoDB.Driver.MongoCollection<SportsFantasy_2._0.Models.User>' does not contain a definition for 'AsQueryable' and the best extension method overload 'System.Linq.Queryable.AsQueryable(System.Collections.IEnumerable)' has some invalid arguments
You are missing a namespace, MongoDB.Driver.Linq, simply add that at the top:
using MongoDB.Driver.Linq;
That specific method is:
LinqExtensionMethods
{
public static IQueryable<T> AsQueryable<T>(this MongoCollection<T> collection);
//...
}
I was getting the same error with with the .NET driver v2.3.0. I removed it and installed v2.2.4 using NuGet and it worked. The error I kept getting:
Method not found: 'MongoDB.Driver.Linq.IMongoQueryable1<!!0> MongoDB.Driver.IMongoCollectionExtensions.AsQueryable(MongoDB.Driver.IMongoCollection1)'.
Related
using Microsoft.EntityFrameworkCore;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Issue>()
.HasMany<Person>(issue => issue.Persons)
.WithMany(person => person.Issues)
.Map(personIssue =>
{
personIssue.MapLeftKey("IssueId");
personIssue.MapRightKey("PersonId");
personIssue.ToTable("IssuePerson");
});
}
public class Issue
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IssueId { get; set; }
[MaxLength(50)]
public string ExternalIdentifier { get; set; } = string.Empty;
[MaxLength(50)]
public string SummaryShort { get; set; } = string.Empty;
[MaxLength(50)]
public string SummaryLong { get; set; } = string.Empty;
[MaxLength(100)]
public string ProblemStatement { get; set; } = string.Empty;
public DateTime WorkAround { get; set; }
[Required]
public DateTime Severity { get; set; }
public DateTime Priority { get; set; }
[MaxLength(50)]
public DateTime DateFound { get; set; }
public DateTime DateReported { get; set; }
public DateTime DateResolved { get; set; }
public ICollection<Person> Persons { get; set; }
= new List<Person>();
public ICollection<Team> Teams { get; set; }
= new List<Team>();
public Person ReportedByPerson { get; set; }
public Team ReportedByTeam { get; set; }
}
public class Person
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }
[MaxLength(50)]
public string FirstName { get; set; } = string.Empty;
[MaxLength(50)]
public string MiddleName { get; set; } = string.Empty;
[MaxLength(50)]
public string LastName { get; set; } = string.Empty;
public ICollection<PersonRole> PersonRole { get; set; }
= new List<PersonRole>();
public ICollection<Location> Locations { get; set; }
= new List<Location>();
public ICollection<Issue> Issues { get; set; }
= new List<Issue>();
}
In this code, the .Map method is flagged with an error
No overload takes 1 argument
I can't seem to find the definition of this method via Visual Studio or Google. Has this changed in EF Core 7?
Code example above came from here: https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
Added the models involved, but please note these tables are involved in other relationships as well.
It is not EF Core. It is EF 6 Map method.
Currently i have the following structure of my classes:
public class StoreElement
{
[Display(Name="ID")]
public int StoreElementId { get; set; }
[Display(Name = "RegalID")]
public string StoreElementCode { get; set; }
[Display(Name = "Regal")]
public string Storage { get; set; }
[Display(Name="Ebene")]
public string Level { get; set; }
[Display(Name = "Fach")]
public string Shelf { get; set; }
[Display(Name = "ESL Tag")]
public string ESLTagId { get; set; }
[Display(Name ="ESL Layout Template")]
public string ESLLayoutValue { get; set; }
[Display(Name = "Eingelagertes Material")]
public List<Material> Materials { get; set; }
}
And this class:
public class Material
{
[Display(Name = "ID")]
public int MaterialId { get; set; }
[Display(Name = "Materialnummer")]
public int? MaterialNumber { get; set; }
[Display(Name = "Auftragsnummer")]
public int? OrderNumber { get; set; }
[Display(Name = "Eingelagert")]
public bool? IsStored { get; set; }
[Display(Name = "Einlagerdatum")]
public DateTime StoredAt { get; set; }
[Display(Name = "Auslagerdatum")]
public DateTime OutsourcedAt { get; set; }
[Display(Name = "Liefertermin")]
public DateTime DeliveryDate { get; set; }
[Display(Name = "Priorisiertes Material")]
public bool PriorityMaterial { get; set; }
public int? StoreElementId { get; set; }
public StoreElement StoreElement { get; set; }
}
A StoreElement can hold a List of Materials. The class Materials contains a property which is a date. Now i would like to order the Storage-Location List by the subproperty date of a list of materials.
I tried something in linq like that:
var myOrderdStorageLocationsByDeliveryDateOfMaterialsSublist = this.MyDatabaseContext.StorageLocations.Include(x=>x.Materials).OrderBy(x=>x.Materials.OrderBy(y=>y.DeliveryDate)).ToList();
But this throws an exception that says "Failed to compare two elements in the array"
Obviously, you need some value from Materials. And OrderBy won't return it.
I would recommend you to get a particular value for sorting StoreElements based on what logic you need: Min, Max or Average for example.
var myOrderdStorageLocationsByDeliveryDateOfMaterialsSublist = this.MyDatabaseContext.StorageLocations
.Include(x=>x.Materials)
.OrderBy(x=>x.Materials.Min(y=>y.DeliveryDate))
.ToList();
I am trying to implement Asp.net Identity 2.0 with DB first.
I have imported my model.edmx into the project. It contains all the tables I need with the correct information and structure.
In the database there is a table called 'FSKUsers' I have edited this to contain the needed fields of the AspNetUsers which is the default table for Identity 2.0
So in my Identity DB Context I have mapped my FskUser class (which is a high level user for Identity sake)
public class IdentityDbContext : IdentityDbContext<FskUser, FskRole, int, FskUserLogin, FskUserRole, FskUserClaim>
{
public IdentityDbContext()
: base("FSK_FskNetworksEntities")
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var userEntity = modelBuilder.Entity<FskUser>();
userEntity.ToTable("FSKUsers", "dbo");
userEntity.Property(p => p.Id).HasColumnName("FSKUserId");
userEntity.Property(p => p.PasswordHash).HasColumnName("Password");
}
public static IdentityDbContext Create()
{
return new IdentityDbContext();
}
}
So basically I want to map the class FskUser to the Data Base table called FSKUser which is also contained in my .edmx model.
When I run the website I get the following error.
The entity type FskUser is not part of the model for the current context
My two POCO classes:
The one from my edmx model:
public partial class FSKUser
{
public FSKUser()
{
this.AspNetUserClaims = new HashSet<AspNetUserClaim>();
this.AspNetUserLogins = new HashSet<AspNetUserLogin>();
this.FSKDevices = new HashSet<FSKDevice>();
this.FSKEventLogs = new HashSet<FSKEventLog>();
this.FSKReports = new HashSet<FSKReport>();
this.FSKTransactions = new HashSet<FSKTransaction>();
this.FSKTriggers = new HashSet<FSKTrigger>();
this.UdlDownloads = new HashSet<UdlDownload>();
this.AspNetRoles = new HashSet<AspNetRole>();
this.FSKCompanies = new HashSet<FSKCompany>();
}
public int FSKUserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public string Password { get; set; }
public string SecurityStamp { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public byte FSKAccessLevelId { get; set; }
public string AddressStreet1 { get; set; }
public string AddressStreet2 { get; set; }
public string AddressStreet3 { get; set; }
public string AddressPostCode { get; set; }
public Nullable<int> CreatorId { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public string ConfirmationToken { get; set; }
public Nullable<bool> IsConfirmed { get; set; }
public Nullable<System.DateTime> LastPasswordFailureDate { get; set; }
public Nullable<int> PasswordFailuresSinceLastSuccess { get; set; }
public Nullable<System.DateTime> PasswordChangedDate { get; set; }
public string PasswordVerificationToken { get; set; }
public string PasswordVerificationTokenExpirationDate { get; set; }
public bool IsDeleted { get; set; }
public Nullable<int> CostCentreId { get; set; }
public Nullable<int> AdminPasswordResetUserId { get; set; }
public Nullable<System.DateTime> PreviousLogInDate { get; set; }
public System.Guid msrepl_tran_version { get; set; }
public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual ICollection<FSKDevice> FSKDevices { get; set; }
public virtual ICollection<FSKEventLog> FSKEventLogs { get; set; }
public virtual ICollection<FSKReport> FSKReports { get; set; }
public virtual ICollection<FSKTransaction> FSKTransactions { get; set; }
public virtual ICollection<FSKTrigger> FSKTriggers { get; set; }
public virtual ICollection<UdlDownload> UdlDownloads { get; set; }
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
public virtual ICollection<FSKCompany> FSKCompanies { get; set; }
}
The one I use in my Identity Config
public class FskUser : IdentityUser<int, FskUserLogin, FskUserRole, FskUserClaim>
{
[Display(Name = "First Name")]
[Required(ErrorMessage = "First Name is Required.")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Last Name is Required.")]
public string LastName { get; set; }
[MaxLength(20)]
[Display(Name = "Cell Number")]
[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone format is not valid.")]
[StringLength(10, ErrorMessage = "The {0} must be 10 numbers long.", MinimumLength = 10)]
public override string PhoneNumber { get; set; }
[Display(Name = "Access Level")]
public byte? FSKAccessLevelId { get; set; }
[Display(Name = "Street Address 1")]
public string AddressStreet1 { get; set; }
[Display(Name = "Street Address 2")]
public string AddressStreet2 { get; set; }
[Display(Name = "Street Address 3")]
public string AddressStreet3 { get; set; }
[Display(Name = "Postal Code")]
public string AddressPostCode { get; set; }
[Display(Name = "Previous Login")]
public Nullable<DateTime> PreviousLogInDate { get; set; }
[Display(Name = "Account Confirmed")]
public Nullable<bool> IsConfirmed { get; set; }
[Display(Name = "Last Password Failier")]
public Nullable<DateTime> LastPasswordFailureDate { get; set; }
[Display(Name = "Password Last Changed")]
public Nullable<DateTime> PasswordChangedDate { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<FskUser, int> manager)
{
//TODO: add option for web and api (to create different auth types
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
When you use Database first approach with edmx file OnModelCreating method is never called. You may check that with debugger.
I have added a user to my mongodb collection called users using this model:
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId _id { get; set; }
[Display(Name = "Password:")]
public string Password { get; set; }
[Display(Name = "Confirm:")]
public string ConfirmPassword { get; set; }
[Display(Name = "Email:")]
public string Email { get; set; }
[Display(Name = "Username:")]
public string UserName { get; set; }
[Display(Name = "Firtname:")]
public string Firstname { get; set; }
[Display(Name = "Lastname:")]
public string Lastname { get; set; }
[Display(Name = "Country:")]
public string Country { get; set; }
[Display(Name = "City:")]
public string City { get; set; }
[Display(Name = "Birthdate:")]
public int Birthdate { get; set; }
public List<Team> Teams { get; set; }
as you can se it also have a list of teams in it. So now im using this code to get the user:
var query_id = Query.EQ("_id", ObjectId.Parse(Session["ID"].ToString()));
User entity = Context.Users.FindOne(query_id);
And now i want to add a list to the mongodb object with the data from my team model:
public int TeamID { get; set; }
public string TeamName { get; set; }
public string UserName { get; set; }
public int LeagueID { get; set; }
public Points Points = new Points();
public List<Player> Player { get; set; }
How do i add the team-modeldata to my userobject in the mongodb collection?
I suggest using LINQ / AutoMapping features of MongoDB.
var databaseClient = new MongoClient(DatabaseConnectionString);
var server = databaseClient.GetServer();
var database = server.GetDatabase("Users");
var collection = database.GetCollection<User>("users");
var user = collection.AsQueryable().First(o => o._id == YOURSESSIONID);
user.Teams.Add(new Team { TeamID = 0, TeamName = "Some Team" });
I have two collections of the following classes that I want to map:
public class Client_Crime_ViewModel
{
public Client_Crime_ViewModel() { }
public Client_Crime_ViewModel(CrimeIncident ci)
{
Id = ci.Id;
CaseNumber = ci.CaseNumber;
DateOfIncident = ci.DateOfIncident;
Description = ci.Description;
}
public Int64 Id
{
get;
set;
}
[Required]
[DisplayName("Case Number")]
public string CaseNumber { get; set; }
[DataType(DataType.Date)]
[Required]
[DisplayName("Date of Incident")]
public string DateOfIncident { get; set; }
[DataType(DataType.MultilineText)]
[Required]
public string Description { get; set; }
}
public class CrimeIncident
{
public Int64 Id { get; set; }
[Required]
public string CaseNumber { get; set; }
[Required]
public string Description { get; set; }
[DataType(DataType.Date)]
public string DateOfIncident { get; set; }
public CrimeIncident() { }
public CrimeIncident(string caseNumber, string dateOfIncident, string description)
{
CaseNumber = caseNumber;
Description = description;
DateOfIncident = dateOfIncident;
}
}
I have tried mapping in both of the following ways:
Method 1:
Mapper.CreateMap<List<Client_Crime_ViewModel>, List<CrimeIncident>>();
List<Client_Crime_ViewModel> cvmList = System.Web.Helpers.Json.Decode<System.Collections.Generic.List<Client_Crime_ViewModel>>(rb.Form["CrimeCollection"]);
List<CrimeIncident> ciList = Mapper.Map<List<Client_Crime_ViewModel>, List<CrimeIncident>>(cvmList);
Method 2:
Mapper.CreateMap<List<Client_Crime_ViewModel>, List<CrimeIncident>>();
List<Client_Crime_ViewModel> cvmList = System.Web.Helpers.Json.Decode<System.Collections.Generic.List<Client_Crime_ViewModel>>(rb.Form["CrimeCollection"]);
List<CrimeIncident> ciList = Mapper.Map<List<CrimeIncident>>(cvmList);
Both methods fail. Debugging reveals that although the element count for cvmList is > 0, the element count for ciList remains at 0.
Any idea what I am doing wrong?
Thanks in advance.
You don't need to create a map for a list, just map the entities.