Hej, FYI detta är skolarbete.
Bakgrund. Jag huller på att skapa en databas med x antal tabeller. I min context klass har jag tre dataset, varav en, Player använder sig av andra klasser, Card och Hand. Detta verkar ha skapat problem när jag försöker använda Add-Migration så måste jag lägga till en
public int Id {get; set;}
för att få det att fungera, men detta leder till att alla klasser med denna kod i sig får sitt egna 'table' i databasen. Är det menat att detta ska hända eller kan jag bli av med det?
Context.
namespace WpfGameDAL
{
public class GameDbContext : DbContext
{
public DbSet<Player> Players { get; set; }
public DbSet<GameSession> Sessions { get; set; }
public DbSet<GameStatistics> Statistics { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(@Server=(localdb)\mssqllocaldb;Database=WpfTestDb);
Debug.WriteLine("Is configured " + options.IsConfigured);
}
}
}
Player.
namespace WpfGameDLL
{
public class Player
{
[Key]
public int Id { get; set; }
[Required]
public string PlayerName { get; set; }
[Required]
public int Wins { get; set; }
[Required]
public int Losses { get; set; }
private string playerId;
private Hand hand;
public Player(string name)
{
playerId = name + GenerateId();
hand = new Hand();
}
public Player()
{
}
public string GenerateId()
{
Random random = new Random();
string id = "";
for (int i = 0; i < 4; i++)
{
id += Convert.ToString(random.Next(0, 10));
}
return id;
}
public Hand Hand
{
get { return hand; }
set { hand = value; }
}
public void ResetHand()
{
hand = new Hand();
}
public string PlayerId
{
get { return playerId; }
set { playerId = value; }
}
public bool AddCard(Card card)
{
bool bust = hand.AddCard(card);
return bust;
}
public int GetSumOfCards()
{
int sum = hand.GetSumOfCards();
return sum;
}
public bool Next()
{
int nrOfCards = hand.NumberOfCards();
if (nrOfCards > 1)
{
return false;
}
return true;
}
public bool Bust()
{
if (!Next())
{
int value = GetSumOfCards();
if (value > 21)
{
return false;
}
return true;
}
else return false;
}
}
}
Hand.
namespace WpfGameDLL
{
public class Hand
{
private List<Card> cards;
public Hand()
{
cards = new List<Card>();
}
public List<Card> GetCards()
{
return cards;
}
public List<Card> Cards
{
get { return cards; }
set { cards = value; }
}
public bool AddCard(Card card)
{
cards.Add(card);
int value = GetSumOfCards();
return CanHit(value);
}
public bool HandBust(int sum)
{
if (sum > 21)
{
return true;
}
return false;
}
public bool CanHit(int sum)
{
if (sum < 21)
{
return true;
}
else return false;
}
public int GetSumOfCards()
{
try
{
int sum = 0;
for (int i = 0; i < cards.Count; i++)
{
sum += cards[i].GetValue();
}
if (HasAce()) //An ace can be either 11 or 1, if the sum is more than 11 than the ace takes the value of 1 else it has the value of 11;
{
if (sum < 10)
{
sum = sum + 10;
}
}
return sum;
}
catch (System.NullReferenceException)
{
}
return 0;
}
public bool HasAce()
{
//In blackjack aces have a special function that changes their value to the total, reqiring this mehtod being included to account for that.
string[] aces = new string[] { "c1", "s1", "h1", "d1" };
for (int i = 0; i < cards.Count; i++)
{
for (int j = 0; j < aces.Length; j++)
{
if (cards[i].GetSuite() == aces[j])
{
return true;
}
}
}
return false;
}
public int NumberOfCards()
{
return cards.Count;
}
}
}
Card.
namespace WpfGameDLL
{
public class Card
{
private string suite;
private int value;
public Card()
{
}
public BitmapImage GetCardBack()
{
BitmapImage img = new BitmapImage(GetPathUri("b2fv"));
return img;
}
public BitmapImage GetCardEdge()
{
Uri uri = GetPathUri("b2pl");
BitmapImage img = new BitmapImage(uri);
return img;
}
public Uri GetPathUri(string fileName)
{
string path = System.IO.Directory.GetCurrentDirectory();
Uri uri = new Uri(path + @\CardGUI" + fileName + .png");
return uri;
}
public Card(string suite)
{
this.suite = suite;
value = (int)Enum.Parse(typeof(EnumSuite), suite);
}
//Kortens suite matchar namnet på deras bilder i bild mappen så denna metod hämtar filvägen till ett korts png fil
//och omvandlar sedan den till en bitmapimage som man kan skicka tillbaka till en xaml class där man kan visa bilden.
public BitmapImage GetCardImage()
{
string path = System.IO.Directory.GetCurrentDirectory();
Uri uri = new Uri(path + @\CardGUI" + suite + .png");
BitmapImage img = new BitmapImage(uri);
return img;
}
public string GetSuite()
{
return suite;
}
public int GetValue()
{
try
{
return value;
}
catch (NullReferenceException)
{
return 0;
}
}
}
}
Hela felmedelandet frå package manager console efter jag skrivit in Add-Migration -Project WpfGameDAL
Add-Migration -Project WpfGameDAL
cmdlet Add-Migration at command pipeline position 1
Supply values for the following parameters:
Name: testMig
Build started...
Build succeeded.
System.InvalidOperationException: The entity type 'Card' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelRuntimeInitializer.Initialize(IModel model, Boolean designTime, IDiagnosticsLogger`1 validationLogger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, ModelCreationDependencies modelCreationDependencies, Boolean designTime)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel(Boolean designTime)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__8_4(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
The entity type 'Card' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.